Quark.Compose (Quark v2.3.2) View Source
Function composition is taking two functions, and joining them together to create a new function. For example:
Examples
iex> sum_plus_one = compose([&(&1 + 1), &Enum.sum/1])
...> sum_plus_one.([1,2,3])
7
In this case, we have joined Enum.sum
with a function that adds one,
to create a new function that takes a list, sums it, and adds one.
Note that composition normally applies from right to left, though Quark
provides the opposite in the form of *_forward
functions.
Link to this section Summary
Functions
Infix compositon operator
Infix "forward" compositon operator
Function composition, from the tail of the list to the head
Function composition
Compose functions, from the head of the list of functions.
Function composition, from the head to tail (left-to-right)
Link to this section Functions
Specs
Infix compositon operator
Examples
iex> sum_plus_one = fn x -> x + 1 end <|> &Enum.sum/1
...> sum_plus_one.([1,2,3])
7
iex> add_one = &(&1 + 1)
...> piped = [1, 2, 3] |> Enum.sum() |> add_one.()
...> composed = [1, 2, 3] |> ((add_one <|> &Enum.sum/1)).()
...> piped == composed
true
Specs
Infix "forward" compositon operator
Examples
iex> sum_plus_one = (&Enum.sum/1) <~> fn x -> x + 1 end
...> sum_plus_one.([1, 2, 3])
7
iex> x200 = (&(&1 * 2)) <~> (&(&1 * 10)) <~> (&(&1 * 10))
...> x200.(5)
1000
iex> add_one = &(&1 + 1)
...> piped = [1, 2, 3] |> Enum.sum() |> add_one.()
...> composed = [1, 2, 3] |> ((&Enum.sum/1) <~> add_one).()
...> piped == composed
true
Specs
Function composition, from the tail of the list to the head
Examples
iex> sum_plus_one = compose([&(&1 + 1), &Enum.sum/1])
...> [1,2,3] |> sum_plus_one.()
7
Specs
Function composition
Examples
iex> sum_plus_one = compose(&(&1 + 1), &Enum.sum/1)
...> [1, 2, 3] |> sum_plus_one.()
7
Specs
Compose functions, from the head of the list of functions.
Examples
iex> sum_plus_one = compose_forward([&Enum.sum/1, &(&1 + 1)])
...> sum_plus_one.([1, 2, 3])
7
Specs
Function composition, from the head to tail (left-to-right)
Examples
iex> sum_plus_one = compose_forward(&Enum.sum/1, &(&1 + 1))
...> [1, 2, 3] |> sum_plus_one.()
7