Funx.Monad
Mix.install([
{:funx, "0.3.0"}
])
The Funx.Monad protocol defines the core monadic operations: ap/2, bind/2, and map/2.
A monad is an abstraction that represents computations as a series of steps. This protocol is designed to be implemented by types that wrap a value and allow chaining of operations while preserving the wrapped context.
Functions
-
map/2: Applies a function to the value within the monad. -
bind/2: Chains operations by passing the unwrapped value into a function that returns another monad. -
ap/2: Applies a monadic function to another monadic value.
Function Examples
alias Funx.Monad
alias Funx.Monad.Maybe
import Funx.Monad.Maybe
map/2
Maps a function over the value inside the monad.
The map/2 function takes a monad m and a function func, applies the function to the value inside m, and returns a new monad
containing the result. The original monadic context is preserved.
Examples
Monad.map(just(2), fn x -> x + 3 end)
In the case of Nothing:
Monad.map(nothing(), fn x -> x + 3 end)
Using the pipe operator:
just(2)
|> Monad.map(&(&1 + 3))
bind/2
Chains a monadic operation.
The bind/2 function takes a monad m and a function func. The function func is applied to the unwrapped value of m,
and must return another monad. The result is the new monad produced by func.
This is the core operation that allows chaining of computations, with the value being passed from one function to the next in a sequence.
Examples
Monad.bind(just(5), fn x -> just(x * 2) end)
In the case of Nothing:
Monad.bind(nothing(), fn _ -> just(5) end)
Using the pipe operator:
just(5)
|> Monad.bind(fn x -> just(x * 2) end)
ap/2
Applies a monadic function to another monadic value.
The function func is expected to be wrapped in a monadic context and is applied to the value m within its own monadic context.
The result is wrapped in the same context as the original monad.
Examples
Monad.ap(just(fn x -> x * 2 end), just(3))
In the case of Nothing:
Monad.ap(nothing(), just(3))