Std.Monad
View source →Monad interface — structures that support sequencing with a failure arm.
A monad is a type constructor m equipped with pure (embed a value)
and and_then (sequence, threading the unwrapped payload and
short-circuiting on the failure arm). and_then is the operation the
binder pipe |x|> desugars to: a |x|> f(x) lowers to
and_then(a, fn(x) -> f(x)) (see docs/BIND_PIPE.md § 7).
Monad is genuinely higher-kinded: its head m has kind
Type -> Type, so pure lifts an a to m(a) and and_then threads
an a -> m(b) through an m(a). The built-in instances cover Result
and Option; additional instances can be declared for user-defined
container types.
A binary constructor such as Result(T, E) is admitted by applying the
head to its payload only — m(a) — with the remaining parameters
(E) filled by a fresh, universally-quantified variable on each
instance method (Result(a, e)). This is what lets one payload-only
interface cover both the unary Option and the binary Result.
Examples
use Std.Monad
and_then(Ok(1), fn(x: Int) -> Result(Int, Atom) = Ok(x + 1)) # => Ok(2)
and_then(Error(:e), fn(x: Int) -> Result(Int, Atom) = Ok(x)) # => Error(:e)
pure(42) # => Ok(42)