monad.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/monad.nix
Module Description
Monadic operations for sequencing and binding effects
Combinators
andThen
Chains two effects using different contexts, discarding the first value.
Like flatMap but the second effect is constant (doesn’t depend on
first value). Useful for sequencing heterogeneous effects.
Type Signature
Fx<T, U> -> Fx<S, V> -> Fx<{fst: S, snd: T}, U>
Parameters
next: Effect to run second (its value is returned)e: Effect to run first (its value is discarded)
Example
provide { fst = 10; snd = "hello"; } (
andThen
(pending (s: immediate s s)) # Returns "hello"
(pending (n: immediate n (n * 2)))
) # => "hello"
See Also
then'- Same-context versionflatMap- When second depends on first value
flatMap
Monadic bind that combines different context requirements.
Unlike mapM where both effects share context, flatMap handles
the case where the first effect needs context S and the continuation
produces effects needing context R. The result requires both.
Type Signature
(V -> Fx<R, U>) -> Fx<S, V> -> Fx<{fst: S, snd: R}, U>
Parameters
f: Continuation producing effect using different contexte: First effect
Example
provide { fst = 10; snd = 5; } (
flatMap
(x: pending (r: immediate r (x + r)))
(pending (s: immediate s s))
) # => 15
Notes
Use mapM when both effects have the same context type.
Use flatMap when combining effects using different requirements.
See Also
mapM- Same-context sequencingandThen- Like flatMap but discards first value
mapM
Monadic bind within the same context type.
Sequences effects where the second depends on the first’s value. Both effects must have the same context type.
Type Signature
(V -> Fx<S, U>) -> Fx<S, V> -> Fx<S, U>
Parameters
f: A function producing an effectV -> Fx<S, U>e: The first effect
Example
# Chain computations
mapM (x: pure (x * 2)) (pure 21) # => Fx producing 42
# State threading
provide { n = 10; }
(mapM
(x: pending (ctx: immediate ctx (x + ctx.n)))
(value 5)) # => 15
Laws
- Left identity:
mapM f (pure x) == f x - Right identity:
mapM pure e == e - Associativity:
mapM g (mapM f e) == mapM (x: mapM g (f x)) e
See Also
flatMap- When continuation has different contextthen'- When first value is ignored
then'
Sequences two effects, discarding the first value.
Runs the first effect for its side effects (state changes), then runs the second effect and returns its value. Named with quote to avoid conflict with reserved words.
Type Signature
Fx<S, U> -> Fx<S, V> -> Fx<S, U>
Parameters
next: Effect to run second (its value is returned)e: Effect to run first (its value is discarded)
Example
then' (pure 42) (pure 1) # => Fx producing 42
See Also
mapM- When second effect depends on first valueandThen- When effects have different contexts
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/monad.nix