Witchcraft.Chain.Proto protocol (Witchcraft v1.0.4) View Source

Protocol for the Elixir.Witchcraft.Chain type class

For this type class's API, please refer to Elixir.Witchcraft.Chain

Link to this section Summary

Functions

Sequentially compose actions, piping values through successive function chains.

Link to this section Types

Link to this section Functions

Link to this function

chain(chainable, link_fun)

View Source

Specs

Sequentially compose actions, piping values through successive function chains.

The applied linking function must be unary and return data in the same type of container as the input. The chain function essentially "unwraps" a contained value, applies a linking function that returns the initial (wrapped) type, and collects them into a flat(ter) structure.

chain/2 is sometimes called "flat map", since it can also be expressed as data |> map(link_fun) |> flatten().

As a diagram:

%Container<data> --- (data -> %Container<updated_data>) ---> %Container<updated_data>

Examples

iex> chain([1, 2, 3], fn x -> [x, x] end)
[1, 1, 2, 2, 3, 3]

iex> [1, 2, 3]
...> |> chain(fn x -> [x, x] end)
...> |> chain(fn y -> [y, 2 * y, 3 * y] end)
[1, 2, 3, 1, 2, 3, 2, 4, 6, 2, 4, 6, 3, 6, 9, 3, 6, 9]

iex> chain([1, 2, 3], fn x ->
...>   chain([x + 1], fn y ->
...>     chain([y + 2, y + 10], fn z ->
...>       [x, y, z]
...>     end)
...>   end)
...> end)
[1, 2, 4, 1, 2, 12, 2, 3, 5, 2, 3, 13, 3, 4, 6, 3, 4, 14]