Witchcraft v1.0.0-beta Witchcraft.Functor View Source
Functors are datatypes that allow the application of functions to their interior values. Always returns data in the same structure (same size, tree layout, and so on).
Please note that bitstrings are not functors, as they fail the functor composition constraint. They change the structure of the underlying data, and thus composed lifting does not equal lifing a composed function. If you need to map over a bitstring, convert it to and from a charlist.
Type Class
An instance of Witchcraft.Functor
must define Witchcraft.Functor.map/2
.
Functor [map/2]
Link to this section Summary
Link to this section Types
Link to this section Functions
<~/2
with arguments flipped.
iex> (fn x -> x + 5 end) <~ [1,2,3]
[6, 7, 8]
Note that the mnemonic is flipped from |>
, and combinging directions can
be confusing. It’s generally recommended to use ~>
, or to keep <~
on
the same line both of it’s arguments:
iex> fn(x, y) -> x + y end <~ [1, 2, 3]
...> |> List.first()
...> |> apply([9])
10
…or in an expression that’s only pointing left:
iex> fn y -> y * 10 end
...> <~ fn x -> x + 55 end
...> <~ [1, 2, 3]
[560, 570, 580]
lift(Witchcraft.Functor.t, (... -> any)) :: Witchcraft.Functor.t
map/2
but with the function automatically curried
Examples
iex> lift([1, 2, 3], fn x -> x + 1 end)
[2, 3, 4]
iex> [1, 2, 3]
...> |> lift(fn x -> x + 55 end)
...> |> lift(fn y -> y * 10 end)
[560, 570, 580]
iex> [1, 2, 3]
...> |> lift(fn(x, y) -> x + y end)
...> |> List.first()
...> |> apply([9])
10
map
a function into one layer of a data wrapper.
There is an autocurrying variant: lift/2
.
Examples
iex> map([1, 2, 3], fn x -> x + 1 end)
[2, 3, 4]
iex> %{a: 1, b: 2} ~> fn x -> x * 10 end
%{a: 10, b: 20}
iex> map(%{a: 2, b: [1, 2, 3]}, fn
...> int when is_integer(int) -> int * 100
...> value -> inspect(value)
...> end)
%{a: 200, b: "[1, 2, 3]"}
replace(Witchcraft.Functor.t, any) :: Witchcraft.Functor.t
Replace all inner elements with a constant value
Examples
iex> replace([1, 2, 3], "hi")
["hi", "hi", "hi"]
Operator alias for lift/2
Example
iex> [1, 2, 3]
...> ~> fn x -> x + 55 end
...> ~> fn y -> y * 10 end
[560, 570, 580]
iex> [1, 2, 3]
...> ~> fn(x, y) -> x + y end
...> |> List.first()
...> |> apply([9])
10