kernel.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/kernel.nix
Module Description
Core kernel primitives for the NFX effect system
Combinators
adapt
The fundamental combinator - everything else builds on this.
adapt is the core primitive that enables all effect transformations.
It simultaneously handles:
- Contravariant mapping of context requirements (what the effect needs)
- Covariant mapping of continuations (what happens given the result)
Type Signature
Fx<S,V> -> (T -> S) -> (T -> S -> V -> Fx<T,U>) -> Fx<T,U>
Parameters
e: The effect to transformcmap: Context mapperT -> S- extracts inner requirement from outer contextfmap: Continuation(T, S, V) -> Fx<T,U>- transforms the result
How It Works
- Creates a pending effect expecting context T
- Applies
cmapto get the inner context S - If effect is immediate, applies
fmapto produce final result - If effect is pending, recursively adapts the continuation
Example
# Double the result of an effect
adapt (pure 21) (s: s) (_t: _s: v: immediate {} (v * 2))
See Also
map- Simpler value transformation (built on adapt)contraMap- Simpler context transformation (built on adapt)
immediate
Creates an immediate (already resolved) effect.
An immediate effect is the terminal case of the Fx type - it carries both a state and a value, meaning it needs no further context to produce its result. This is one of two fundamental constructors for the Fx algebraic data type.
Type Signature
state -> value -> Fx<state, value>
Parameters
state: The current state/context that was used to produce the valuevalue: The computed result
Example
immediate {} 42 # Effect holding value 42 with empty state
immediate { count = 1; } "done" # Effect with state and string value
See Also
pending- The other Fx constructor for suspended computationsrunFx- Evaluates an effect to extract its value
pending
Creates a pending (suspended) effect awaiting context.
A pending effect wraps an “ability” - a function that will be called given context to produce the next step of computation. This is the mechanism by which effects express their requirements: the ability requests something from the context.
Type Signature
(context -> Fx<S, V>) -> Fx<S, V>
Parameters
ability: A functioncontext -> Fx<S, V>that consumes context and produces the next computation step
Example
# Effect that reads a number from context and doubles it
pending (n: immediate n (n * 2))
# Effect requesting an attribute from context
pending (ctx: immediate ctx ctx.username)
See Also
immediate- The terminal case, already has its valueadapt- The fundamental combinator for transforming effects
runFx
Evaluates an effect to extract its final value.
This is the interpreter that runs an effect computation. It only works
when all context requirements have been satisfied (state is unit/empty).
The function loops until reaching an immediate result, feeding empty
context {} to any pending abilities.
Type Signature
Fx<{}, V> -> V
Parameters
e: An effect with no remaining context requirements
Returns
The final computed value
Example
runFx (pure 42) # => 42
runFx (provide 10 (pending (n: immediate n (n * 2)))) # => 20
Notes
Before calling runFx, all context requirements must be satisfied using
provide or similar combinators. Calling runFx on an effect that still
has requirements will fail when the ability tries to access missing context.
See Also
provide- Satisfies context requirements before evaluationpure- Creates an effect ready for immediate evaluation
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/kernel.nix
basic.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/basic.nix
Module Description
Basic effect constructors for lifting values
Combinators
pure
Creates a pure (effect-free) value with no context requirements.
This is the simplest way to lift a plain value into the effect system.
The resulting effect is immediately available and requires no context.
Equivalent to immediate {}.
Type Signature
V -> Fx<{}, V>
Parameters
value: Any value to wrap in an effect
Example
pure 42 # => Fx<{}, Int>
pure "hello" # => Fx<{}, String>
runFx (pure 42) # => 42
See Also
value- Similar but preserves any context typeimmediate- Lower-level constructor used internally
value
Creates an effect that produces a value while preserving any context.
Unlike pure which requires empty context, value works polymorphically
over any context type. The context passes through unchanged.
Type Signature
V -> Fx<S, V> (for any S)
Parameters
v: The value to produce
Example
# Works in any context
provide { x = 1; } (value 42) # => 42
# Useful in sequencing when you need a constant
mapM (x: value (x * 2)) someEffect
See Also
pure- When you know context is emptyfunc- When value depends on state
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/basic.nix
functor.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/functor.nix
Module Description
Functor operations for transforming effects
Combinators
contraMap
Transforms context requirements (contravariant mapping).
Adapts an effect that needs context Inner to work in context Outer.
This is how effects compose when they have different requirements -
you can zoom into a larger context to satisfy a smaller requirement.
Type Signature
(Outer -> Inner) -> (Outer -> Inner -> Outer) -> Fx<Inner,V> -> Fx<Outer,V>
Parameters
getter: Extracts inner context from outerOuter -> Innersetter: Updates outer context given new inner stateOuter -> Inner -> Outere: Effect requiringInner
Example
# Effect needing a number
inner = pending (n: immediate n (n * 2))
# Adapt to work in record containing the number
outer = contraMap
(ctx: ctx.num)
(ctx: n: ctx // { num = n; })
inner
runFx (provide { num = 5; other = "x"; } outer) # => 10
See Also
lift- Named attribute version of contraMaplens.zoomOut- Lens-based focusing
map
Functor map: transforms the value inside an effect.
Applies a pure function to the result of an effect without changing the effect’s context requirements. This is the standard functor fmap.
Type Signature
(V -> U) -> Fx<S, V> -> Fx<S, U>
Parameters
f: A pure functionV -> Ue: The effect to transform
Example
map (x: x * 2) (pure 21) # => Fx producing 42
map toString (pure 42) # => Fx producing "42"
Laws
- Identity:
map id e == e - Composition:
map (f . g) e == map f (map g e)
See Also
mapM- When transformation produces an effectcontraMap- For transforming context instead of value
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/functor.nix
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
provide.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/provide.nix
Module Description
Context provision and manipulation
Combinators
func
Creates an effect from a function on state.
This is a convenience combinator that reads the state and applies
a pure function to produce the value. Equivalent to map f state.get.
Type Signature
(S -> V) -> Fx<S, V>
Parameters
f: A pure function from state to value
Example
provide 10 (func (n: n * 2)) # => 20
provide { x = 5; } (func (ctx: ctx.x + 1)) # => 6
See Also
state.get- Just reads state without transformationmap- Transforms value of an existing effect
provide
Satisfies a context requirement, eliminating it.
This is the primary way to “run” effects - by providing the context they need. The provided value becomes the context for the inner effect, and the resulting effect has no requirements for that context.
Type Signature
S -> Fx<S, V> -> Fx<T, V> (for any T)
Parameters
s: The context value to providee: Effect that requires contextS
Example
# Effect needing a number
double = pending (n: immediate n (n * 2))
# Provide the number to get a runnable effect
runFx (provide 21 double) # => 42
# Provide a record context
runFx (provide { x = 5; y = 3; }
(pending (ctx: immediate ctx (ctx.x + ctx.y)))) # => 8
See Also
provideLeft- Provides left side of paired contextprovidePart- Provides part using custom getter/setter
provideLeft
Provides the left component of a paired context requirement.
When an effect requires {fst: A, snd: B}, this provides the A
part, leaving an effect that only requires B.
Type Signature
A -> Fx<{fst: A, snd: B}, V> -> Fx<B, V>
Parameters
a: Value for the left/first context componente: Effect requiring paired context
Example
provide 20 (
provideLeft 10
(pending (ctx: immediate ctx (ctx.fst + ctx.snd)))
) # => 30
See Also
provide- Provides entire contextandNil- Extends context given unit on right
providePart
Provides part of a context using custom getter/setter.
A generalized version of provide that allows partial satisfaction
of context requirements using custom lensing functions.
Type Signature
A -> (A -> B -> S) -> (B -> S -> B) -> Fx<S, V> -> Fx<B, V>
Parameters
a: Value to inject into contextcmap: CombinesAand remaining contextBto form full contextSfmap: Extracts remaining context from result statee: Effect requiring full contextS
Example
provide 5 (
providePart 10
(a: b: { x = a; y = b; })
(_b: ctx: ctx.y)
(pending (ctx: immediate ctx (ctx.x + ctx.y)))
) # => 15
See Also
provide- Simpler full context provisionprovideLeft- Standard paired context provision
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/provide.nix
sequence.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/sequence.nix
Module Description
Do-notation for readable effect sequencing
Combinators
do
Monadic do-notation for composing effects with binding.
Takes a list of functions V -> Fx<S, U> and chains them left-to-right,
threading values through. Each function receives the result of the previous
computation. Much more readable than nested mapM calls.
The first function receives null as input (use _: to ignore).
The last function’s result becomes the final value.
Type Signature
[V -> Fx<S, V>] -> Fx<S, V>
Parameters
steps: List of functions to chain
Example
# Instead of nested mapM:
mapM (user:
mapM (posts:
mapM (comments:
pure (processAll user posts comments)
) (getComments posts)
) (getPosts user)
) getUser
# Use do notation:
do [
(_: getUser)
(user: getPosts user)
(posts: getComments posts)
(comments: pure (processAll user posts comments))
]
See Also
do'- Sequence effects without bindingmapM- Single monadic bindthen'- Sequence ignoring first value
do'
Sequence effects left-to-right, returning the last value.
Takes a list of effects and runs them in order, discarding intermediate values. Useful for side effects (state changes, logging) when you only care about the final result.
More readable than nested then' calls.
Type Signature
[Fx<S, V>] -> Fx<S, V>
Parameters
effects: List of effects to sequence
Example
# Instead of nested then':
then' result (
then' (state.modify inc) (
then' (tell "starting") (
tell "init"
)))
# Use do' notation:
do' [
(tell "init")
(tell "starting")
(state.modify inc)
result
]
See Also
do- With value bindingthen'- Sequence two effects
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/sequence.nix
state
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/state.nix
Module Description
Built-in state effect providing get/set/modify operations.
The state effect is a fundamental capability that allows reading and writing to a mutable state. In NFX, state is managed through the context mechanism - the state IS the context.
Namespace Contents
get- Reads the current stateset- Replaces the state with a new valuemodify- Transforms state with a pure functionmodifyM- Transforms state with an effectful function
Example
provide 10 (
mapM (old:
then' (state.get)
(state.modify (x: x + 1))
) state.get
) # State goes 10 -> 11, returns 11
See Also
func- Alternative for read-only state accesscontext- For named attribute-based state
Combinators
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/state.nix
context
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/context.nix
Module Description
Context manipulation utilities for attribute-based state
Combinators
has
Extracts a named attribute from a context.
A utility function for working with attrset-based contexts. In Nix, any attrset naturally “has” its attributes, so this is simply attribute access.
Type Signature
AttrSet -> String -> Value
Parameters
ctx: An attrset contextname: Name of the attribute to extract
Example
has { x = 42; y = 1; } "x" # => 42
See Also
put- Updates an attribute in contextlift- Uses has/put implicitly for effect lifting
lift
Lifts an effect to work with larger contexts.
An effect requiring type A can run in any context that has an
attribute containing A. This is the standard way to compose effects
that work on different parts of a shared context.
Type Signature
String -> Fx<A, V> -> Fx<Ctx, V>
where Ctx is an attrset containing attribute name: A
Parameters
name: The attribute name in the larger contexte: Effect requiring the inner type
Example
runFx (
provide { num = 10; other = "x"; } (
lift "num"
(pending (n: immediate n (n * 3)))
)
) # => 30
How It Works
Uses contraMap to:
- Extract the named attribute for the inner effect
- Update the named attribute with any state changes
See Also
contraMap- Lower-level context transformationlens.zoomOut- Lens-based version
put
Updates a named attribute in a context.
Returns a new attrset with the specified attribute updated. If the attribute doesn’t exist, it is added.
Type Signature
AttrSet -> String -> Value -> AttrSet
Parameters
ctx: The original context attrsetname: Name of the attribute to updatevalue: New value for the attribute
Example
put { x = 1; } "x" 42 # => { x = 42; }
put { x = 1; } "y" 2 # => { x = 1; y = 2; }
See Also
has- Reads an attribute from contextstate.set- Sets the entire state, not just an attribute
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/context.nix
handlers
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/handlers.nix
Module Description
Effect handlers and middleware
Combinators
via
Applies a handler to an effect.
A handler is any function that transforms effects, typically
Fx<A,U> -> Fx<B,V>. This combinator simply applies the handler,
providing a named operation for documentation and readability.
Type Signature
(Fx<A,U> -> Fx<B,V>) -> Fx<A,U> -> Fx<B,V>
Parameters
handler: A function that transforms effectse: The effect to handle
Example
# Apply a mapping handler
via (map (x: x + 1)) (pure 41) # => Fx producing 42
# Chain multiple handlers
via (map toString) (via (map (x: x * 2)) (pure 21))
Notes
While via handler e is equivalent to handler e, using via
makes the intent clearer and enables future middleware patterns.
See Also
map,contraMap- Common handlersprovide- Handler that eliminates requirements
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/handlers.nix
lens
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/lens.nix
Module Description
Lens utilities for focusing on parts of larger contexts.
Lenses are a powerful abstraction for accessing and updating nested data structures. A lens encapsulates a getter and setter pair, enabling effects to work with focused subparts of their context.
Lens Structure
A lens is an attrset with:
get : A -> B- extracts the focused partset : A -> B -> A- updates the focused part
Example
let
l = lens.fromAttr "x";
in
l.get { x = 42; y = 1; } # => 42
l.set { x = 1; y = 2; } 99 # => { x = 99; y = 2; }
See Also
contraMap- Lower-level context transformationlift- Simple attribute-based lifting
Combinators
compose
Chains two lenses for nested access.
Composes two lenses to create a lens that focuses through both, enabling access to deeply nested structures in a composable way.
Type Signature
Lens S A -> Lens A B -> Lens S B
Parameters
outer: Lens from S to Ainner: Lens from A to B
Example
# Focus on x.y in nested structure
let xLens = lens.fromAttr "x";
yLens = lens.fromAttr "y";
xyLens = lens.compose xLens yLens;
in xyLens.get {x = {y = 42;};} # => 42
See Also
fromAttr- Create attribute lenseszoomOut- Use composed lenses with effects
fromAttr
Creates a lens focusing on a named attribute.
Provides getter/setter for accessing an attribute by name within an attribute set. The setter preserves all other attributes.
Type Signature
String -> Lens {name: A, ...} A
Parameters
name: Name of attribute to focus on
Example
let xLens = lens.fromAttr "x";
in xLens.get {x = 42; y = 1;} # => 42
xLens.set {x = 1; y = 2;} 99 # => {x = 99; y = 2;}
See Also
zoomOut- Use lens with effectscompose- Nest attribute access
left
Lens focusing on the fst component of a pair.
Provides access to the first element of a pair structure, commonly used with paired contexts like state + accumulator.
Type Signature
Lens {fst: A, snd: B} A
Example
lens.left.get {fst = 42; snd = 1;} # => 42
lens.left.set {fst = 1; snd = 2;} 99
# => {fst = 99; snd = 2;}
See Also
right- Focus on second componentpair.fst- Direct accessor
make
Creates a lens from getter and setter functions.
A lens provides composable access to nested data structures. It consists of a getter (extracting a value) and setter (updating a value immutably).
Type Signature
(S -> A) -> (S -> A -> S) -> Lens S A
Parameters
get: Function to extract value from structureset: Function to update value in structure
Example
# Lens for first list element
lens.make (list.head) (list: v: [v] ++ (list.tail list))
See Also
fromAttr- Lens for attribute accesscompose- Combine lenses
right
Lens focusing on the snd component of a pair.
Provides access to the second element of a pair structure, commonly used with paired contexts like state + accumulator.
Type Signature
Lens {fst: A, snd: B} B
Example
lens.right.get {fst = 1; snd = 42;} # => 42
lens.right.set {fst = 1; snd = 2;} 99
# => {fst = 1; snd = 99;}
See Also
left- Focus on first componentpair.snd- Direct accessor
zoomIn
Like zoomOut but for continuations (reverse direction).
Adapts a continuation that modifies small context A to work with larger context S via a lens. The continuation can update its portion while preserving the rest of S.
Type Signature
Lens S A -> (A -> Fx<A, V>) -> Fx<S, V> -> Fx<S, V>
Parameters
l: Lens from S to Ainner: Continuation producing effect from Ae: Source effect
Example
let countLens = fromAttr "count";
in zoomIn countLens (n: pure (n + 1)) (pure 0)
# Increments count while preserving other fields
See Also
zoomOut- For effectsmapM- Transform with effects
zoomOut
Adapts an effect to work with a larger context via a lens.
Takes an effect requiring small context A and adapts it to work with larger context S, using a lens to focus on the A within S. The effect sees only its portion while outer context provides the rest.
Type Signature
Lens S A -> Fx<A, V> -> Fx<S, V>
Parameters
l: Lens from S to Ae: Effect requiring context A
Example
# Effect needs just "num", but context has more
zoomOut (fromAttr "num") (pending (n: immediate n (n * 2)))
# Now works with {num = 10; other = ...;}
See Also
zoomIn- For continuationscontraMap- General context transformation
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/lens.nix
pair
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/pair.nix
Module Description
Pair utilities for composing context requirements.
When effects have different requirements, pair combines them into
a single context {fst: A, snd: B}. This module provides utilities
for creating and manipulating these paired contexts.
Pair Structure
A pair is an attrset with fst and snd attributes.
See Also
flatMap- Combines effects with different requirementsandSwap,andNil- Context transformations using pairs
Combinators
bwd
Swaps pair components (backward direction).
Same as swap but named for directional symmetry with fwd.
Useful in bidirectional transformations or when reversing
context orderings.
Type Signature
{fst: A, snd: B} -> {fst: B, snd: A}
Parameters
p: A pair structure
Example
pair.bwd {fst = 1; snd = 2;} # => {fst = 2; snd = 1;}
See Also
swap- Same operationfwd- Identity (no swap)
fst
Extracts the first component of a pair.
Type Signature
{fst: A, snd: B} -> A
Parameters
p: A pair structure
Example
pair.fst {fst = 42; snd = 1;} # => 42
pair.fst (pair.make "x" "y") # => "x"
See Also
snd- Extract second componentmake- Create pairs
fwd
Identity function on pairs (forward direction).
Returns the pair unchanged. Provided for symmetry with bwd
and for explicit control flow in pair transformations.
Type Signature
{fst: A, snd: B} -> {fst: A, snd: B}
Parameters
p: A pair structure
Example
pair.fwd {fst = 1; snd = 2;} # => {fst = 1; snd = 2;}
See Also
bwd- Swap (reverse direction)swap- Same as bwd
make
Creates a pair from two values.
Pairs are fundamental structures in NFX for managing paired contexts (like state and accumulator). This constructs a pair with given values as the first and second components.
Type Signature
A -> B -> {fst: A, snd: B}
Parameters
a: Value for first componentb: Value for second component
Example
pair.make 1 2 # => {fst = 1; snd = 2;}
pair.make "x" [1 2] # => {fst = "x"; snd = [1 2];}
See Also
fst,snd- Extract componentsswap- Reverse components
nest
Restructures nested pairs from right-associated to left-associated.
Transforms (A, (B, C)) to ((A, B), C), moving nesting from
right to left. Useful for normalizing paired contexts or adapting
between different effect compositions.
Type Signature
{fst: A, snd: {fst: B, snd: C}} -> {fst: {fst: A, snd: B}, snd: C}
Parameters
p: Right-nested pair structure
Example
nest {fst = 1; snd = {fst = 2; snd = 3;}}
# => {fst = {fst = 1; snd = 2;}; snd = 3;}
See Also
unnest- Opposite transformation
snd
Extracts the second component of a pair.
Type Signature
{fst: A, snd: B} -> B
Parameters
p: A pair structure
Example
pair.snd {fst = 1; snd = 42;} # => 42
pair.snd (pair.make "x" "y") # => "y"
See Also
fst- Extract first componentmake- Create pairs
swap
Swaps the components of a pair.
Exchanges first and second components, useful when adapting between different context orderings or symmetrizing operations.
Type Signature
{fst: A, snd: B} -> {fst: B, snd: A}
Parameters
p: A pair structure
Example
pair.swap {fst = 1; snd = 2;} # => {fst = 2; snd = 1;}
pair.swap (pair.make "a" "b") # => {fst = "b"; snd = "a";}
See Also
bwd- Alias for swapfwd- Identity (no swap)
unnest
Restructures nested pairs from left-associated to right-associated.
Transforms ((A, B), C) to (A, (B, C)), moving nesting from
left to right. Inverse of nest, useful for adapting effect
context structures.
Type Signature
{fst: {fst: A, snd: B}, snd: C} -> {fst: A, snd: {fst: B, snd: C}}
Parameters
p: Left-nested pair structure
Example
unnest {fst = {fst = 1; snd = 2;}; snd = 3;}
# => {fst = 1; snd = {fst = 2; snd = 3;}}
See Also
nest- Opposite transformation
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/pair.nix
request
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/request.nix
Module Description
Ability request mechanism
Combinators
request
Requests an ability by name from the context.
This is the primary mechanism for invoking capabilities. The context must provide an attribute with the given name, which should be a function (ability) that handles the input and returns an effect.
Type Signature
String -> Input -> Fx<{name: Input -> Fx<S,O>}, O>
Parameters
name: Name of the ability to invokeinput: Input to pass to the ability
Example
runFx (
provide { double = x: pure (x * 2); }
(request "double" 21)
) # => 42
How It Works
- Creates a pending effect
- When evaluated, extracts the ability from context by name
- Calls the ability with the input
- Returns the ability’s result
Notes
Abilities are effectful handlers - they receive input and return
effects. For pure functions, use arrow.request instead.
See Also
arrow.request- For pure functions in contextprovide- Supplies abilities to effects
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/request.nix
zip
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/zip.nix
Module Description
Zip utilities for combining effects
Combinators
zip
Combines two effects into one producing a pair of values.
Both effects share the same context type. The result is an effect
producing {fst: V1, snd: V2} containing both values.
Type Signature
Fx<S, V2> -> Fx<S, V1> -> Fx<S, {fst: V1, snd: V2}>
Parameters
other: Second effect (providessnd)e: First effect (providesfst)
Example
runFx (zip (pure 2) (pure 1)) # => { fst = 1; snd = 2; }
Notes
The order may seem reversed because it’s designed for piping:
e |> zip other runs e first, then other.
See Also
zipLeft- Keeps only first valuezipRight- Keeps only second value
zipLeft
Combines two effects, keeping only the first value.
Runs both effects in sequence but discards the second value. Useful when the second effect is run only for its side effects.
Type Signature
Fx<S, V2> -> Fx<S, V1> -> Fx<S, V1>
Parameters
other: Second effect (value discarded)e: First effect (value kept)
Example
runFx (zipLeft (pure 2) (pure 1)) # => 1
See Also
zip- Keeps both valueszipRight- Keeps second valuethen'- Similar but second effect runs first conceptually
zipRight
Combines two effects, keeping only the second value.
Runs both effects in sequence but discards the first value. Useful when the first effect is run only for its side effects.
Type Signature
Fx<S, V2> -> Fx<S, V1> -> Fx<S, V2>
Parameters
other: Second effect (value kept)e: First effect (value discarded)
Example
runFx (zipRight (pure 2) (pure 1)) # => 2
See Also
zip- Keeps both valueszipLeft- Keeps first value
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/zip.nix
arrow
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/arrow.nix
Module Description
Arrow utilities for pure function capabilities.
Arrows are simpler than abilities - they are pure functions that can
be stored in context and requested by name. Unlike abilities which
return effects, arrows are just A -> B functions.
Namespace Contents
new- Creates an arrow from a pure functionrequest- Requests an arrow by name and applies itadapt- Transforms an arrow with pre/post functions
Difference from Abilities
- Ability:
Input -> Fx<S, Output>(effectful) - Arrow:
Input -> Output(pure)
Example
runFx (
provide { double = x: x * 2; }
(arrow.request "double" 21)
) # => 42
See Also
request- For effectful abilitiesfunc- For state-dependent pure functions
Combinators
adapt
Transforms an arrow with pre/post processing functions.
Wraps an arrow with preprocessing (contramap) and postprocessing (map) functions, creating a new arrow with adapted types.
Type Signature
(A' -> A) -> (B -> B') -> Arrow A B -> Arrow A' B'
Parameters
cmap: Preprocess input (A’ -> A)fmap: Postprocess output (B -> B’)f: Original arrowi: Input value
Example
let inc = x: x + 1;
adapted = arrow.adapt (x: x * 2) (x: x * 10) inc;
in adapted 5 # => (5 * 2 + 1) * 10 = 110
See Also
map- Transform effect outputscontraMap- Transform effect inputs
new
Creates an arrow from a pure function.
Arrows are pure functions (A -> B) that can be stored in context
and requested by name. Unlike abilities which return effects,
arrows perform simple transformations.
Type Signature
(A -> B) -> Arrow A B
Parameters
f: Pure function to wrap as arrow
Example
let double = arrow.new (x: x * 2);
in double 21 # => 42
# Store in context for later use
provide {double = arrow.new (x: x * 2);} ...
See Also
request- Retrieve arrow from contextadapt- Transform arrows
request
Requests an arrow by name from context and applies it.
Retrieves a stored arrow function from the context and applies it to an input value, returning the result wrapped in an effect.
Type Signature
String -> A -> Fx<{name: Arrow A B}, B>
Parameters
name: Name of arrow in contexti: Input value
Example
runFx (
provide {double = arrow.new (x: x * 2);} (
arrow.request "double" 21
)
) # => 42
See Also
new- Create arrowsrequest.request- Request abilities (returns effects)
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/arrow.nix
and
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/and.nix
Module Description
Pair context transformation utilities
Combinators
andCollapse
Collapses a paired context where both parts are the same type.
When an effect requires {fst: S, snd: S}, this transforms it to
require just S, duplicating the single context to satisfy both sides.
Type Signature
Fx<{fst: S, snd: S}, V> -> Fx<S, V>
Parameters
e: Effect requiring paired same-type context
Example
runFx (
provide 10 (
andCollapse (
pending (p: immediate p (p.fst + p.snd))
)
)
) # => 20 (10 + 10)
See Also
andNil- Extends with unit insteadandSwap- Swaps pair components
andNil
Extends an effect’s context with unit on the right.
Transforms an effect requiring S to one requiring {fst: S, snd: {}}.
This is useful for uniformity when combining with effects that use
paired contexts.
Type Signature
Fx<S, V> -> Fx<{fst: S, snd: {}}, V>
Parameters
e: Effect to extend
Example
runFx (
provide { fst = 10; snd = {}; } (
andNil (pending (n: immediate n (n * 2)))
)
) # => 20
See Also
andCollapse- Opposite direction (merges same-type pairs)flatMap- Creates paired context requirements
andSwap
Swaps the components of a paired context requirement.
Transforms an effect requiring {fst: A, snd: B} to one requiring
{fst: B, snd: A}. Useful for reordering context structure.
Type Signature
Fx<{fst: A, snd: B}, V> -> Fx<{fst: B, snd: A}, V>
Parameters
e: Effect requiring paired context
Example
runFx (
provide { fst = "hello"; snd = 10; } (
andSwap (
pending (p: immediate p p.fst)
)
)
) # => 10 (was in snd, now accessed as fst)
See Also
pair.swap- Underlying pair operationandCollapse- Merges same-type pairs
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/and.nix
acc
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/acc.nix
Module Description
Accumulator pattern for threading accumulated values through effects.
The accumulator pattern allows collecting results as effects execute, maintaining an accumulator value in the context that effects can read and update. Useful for gathering build artifacts, tracking dependencies, logging, or any scenario where you need to collect information across effect invocations.
Pattern
Effects using accumulator run in {acc, state} context where:
acc- The accumulator value being threaded throughstate- The actual program state
See Also
state- For stateful computations without accumulationmapM- For chaining effects
Combinators
accumulate
Adds an item to the accumulator in context.
Uses the provided accumulator function to add an item to the
current accumulator value. Must be used within collectWith.
Type Signature
(A -> B -> Fx<S, A>) -> B -> Fx<{acc: A, state: S}, {}>
Parameters
accFn: Accumulator functionitem: Item to add to accumulator
Example
runFx (collectWith [] acc.list (
flatMap (x: accumulate acc.list x *> pure x) (pure 42)
)) # => {acc = [42]; value = 42;}
See Also
collectWith- Set up custom accumulationcollect- Standard list accumulation
collect
Threads accumulator through effect execution.
Executes an effect while maintaining an accumulator in the context.
The effect can call accumulate to add items. Returns both the
final accumulator and the effect’s value.
Type Signature
A -> Fx<{acc: A}, V> -> Fx<{}, {acc: A, value: V}>
Parameters
initial: Initial accumulator valuee: Effect to execute
Example
runFx (collect [] (
mapM (x: accumulate x) (pure [1 2 3])
)) # => {acc = [1 2 3]; value = [1 2 3];}
See Also
collectWith- Use custom accumulator functionwithAccumulator- Extract only accumulator
collectWith
Collects with a custom accumulation function.
Like collect but allows specifying a custom accumulator function
instead of using the default list append. Useful for custom
accumulation strategies (sum, product, merge, etc.).
Type Signature
A -> (A -> B -> Fx<S, A>) -> Fx<{acc: A} & S, V> -> Fx<S, {acc: A, value: V}>
Parameters
initial: Initial accumulator valueaccFn: Function to accumulate itemse: Effect to execute
Example
# Sum accumulator
collectWith 0 (acc: x: pure (acc + x)) ...
# Custom merge accumulator
collectWith {} (acc: x: pure (acc // x)) ...
See Also
collect- Standard list collectionoption,list,set- Built-in accumulators
list
List accumulator that appends items.
Implements accumulation by appending each new item to the end of the list. The standard accumulator for collecting multiple values during effect execution.
Type Signature
[A] -> A -> Fx<{}, [A]>
Parameters
current: Current listitem: Item to append
Example
runFx (acc.list [] 1) # => [1]
runFx (acc.list [1 2] 3) # => [1 2 3]
See Also
collect- Thread list accumulatorwithAccumulator- Extract only accumulator
option
Option accumulator that replaces with new value.
Implements accumulation semantics where each new item completely replaces the current accumulator value. Useful for tracking “latest value” or implementing optional results.
Type Signature
A -> A -> Fx<{}, A>
Parameters
current: Current accumulator (ignored)item: New value to use
Example
runFx (acc.option null 42) # => 42
runFx (acc.option 1 2) # => 2
See Also
list- Append accumulationcollect- Thread accumulator through effects
set
Attribute set accumulator that merges attributes.
Implements accumulation by merging new attributes into the current set. Later values override earlier ones on key conflicts, following Nix’s standard merge semantics.
Type Signature
{...A} -> {...B} -> Fx<{}, {...A, ...B}>
Parameters
current: Current attribute setitem: Attributes to merge
Example
runFx (acc.set {a = 1;} {b = 2;}) # => {a = 1; b = 2;}
runFx (acc.set {a = 1;} {a = 2;}) # => {a = 2;}
See Also
list- List accumulationcollectWith- Use custom accumulator
withAccumulator
Runs effect and returns only the accumulator value.
Like collect but discards the effect’s result value, returning
only the final accumulator. Useful when the accumulation itself
is the desired output.
Type Signature
A -> Fx<{acc: A}, V> -> Fx<{}, A>
Parameters
initial: Initial accumulator valuee: Effect to execute
Example
runFx (withAccumulator [] (
pending (ctx: immediate {...} 42)
)) # => [items...] (discards 42)
See Also
collect- Returns both accumulator and valuecollectWith- With custom accumulator
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/acc.nix
stream-stream-core.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-core.nix
Module Description
Stream constructors - building streams from values and lists
Combinators
done
Creates a terminated (empty) stream.
Represents the end of a stream - no more elements to produce. This is the base case for stream recursion.
Type Signature
Fx<{}, Step<{}, V>>
Example
eval done.value # => { more = false; }
See Also
more- Continue stream with valuefromList- Create from list (empty list -> done)
fromList
Converts a list to a stream.
Creates a stream that yields each list element in order. Empty list produces a terminated stream.
Type Signature
[V] -> Stream<{}, V>
Parameters
list: List to convert
Example
runFx (toList (fromList [1 2 3])) # => [1 2 3]
runFx (fromList []) # => { more = false; }
See Also
toList- Convert stream to listsingleton- Single element stream
more
Creates a stream step with value and continuation.
Produces a stream that yields one value and continues with the next stream. The continuation is not evaluated until needed, enabling lazy, infinite streams.
Type Signature
V -> Stream<S, V> -> Fx<{}, Step<S, V>>
Parameters
value: Value to yieldnext: Continuation stream (lazy)
Example
more 1 (more 2 (more 3 done))
# Stream of [1, 2, 3]
See Also
done- Terminate streamfromList- Build from list
repeat
Repeats an effect n times as a stream.
Creates a stream that executes the same effect n times, yielding each result. Useful for effectful generation.
Type Signature
Int -> Fx<S, V> -> Stream<S, V>
Parameters
n: Number of times to repeateffect: Effect to execute
Example
runFx (provide 5 (
toList (repeat 3 state.get)
)) # => [5 5 5]
See Also
forEach- Execute for each elementmap- Transform elements
singleton
Creates a single-element stream.
Type Signature
V -> Stream<{}, V>
Parameters
value: Single value to yield
Example
runFx (toList (singleton 42)) # => [42]
See Also
fromList- Multiple elementsdone- No elements
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-core.nix
stream-stream-transform.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-transform.nix
Module Description
Stream transformation operations - mapping and filtering
Combinators
filter
Keeps only elements matching a predicate.
Lazily filters stream, skipping elements that don’t match. May need to evaluate multiple steps to find next match.
Type Signature
(V -> Bool) -> Stream<S, V> -> Stream<S, V>
Parameters
pred: Predicate functionstream: Source stream
Example
runFx (toList (filter (x: x > 2) (fromList [1 2 3 4])))
# => [3 4]
See Also
takeWhile- Take until predicate failsmap- Transform all elements
map
Transforms each element in a stream.
Applies a pure function to every value in the stream, preserving structure and laziness.
Type Signature
(V -> U) -> Stream<S, V> -> Stream<S, U>
Parameters
f: Transformation functionstream: Source stream
Example
runFx (toList (map (x: x * 2) (fromList [1 2 3])))
# => [2 4 6]
See Also
filter- Select elementsflatMap- Transform and flatten
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-transform.nix
stream-stream-limit.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-limit.nix
Module Description
Stream limiting operations - taking first n elements or while condition holds
Combinators
take
Takes first n elements from stream.
Terminates after n elements even if source continues. Enables working with infinite streams.
Type Signature
Int -> Stream<S, V> -> Stream<S, V>
Parameters
n: Number of elements to takestream: Source stream
Example
runFx (toList (take 2 (fromList [1 2 3 4])))
# => [1 2]
See Also
takeWhile- Take until conditionfilter- Conditional selection
takeWhile
Takes elements while predicate holds.
Terminates on first element that doesn’t match predicate.
Type Signature
(V -> Bool) -> Stream<S, V> -> Stream<S, V>
Parameters
pred: Predicate to teststream: Source stream
Example
runFx (toList (takeWhile (x: x < 3) (fromList [1 2 3 4])))
# => [1 2]
See Also
take- Take fixed numberfilter- Keep all matching
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-limit.nix
stream-stream-reduce.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-reduce.nix
Module Description
Stream reduction operations - folding, collecting, and iterating
Combinators
fold
Reduces stream to single value with effectful accumulator.
Threads accumulator through stream, applying function to each element. The accumulator function can be effectful.
Type Signature
A -> (A -> V -> Fx<S, A>) -> Stream<S, V> -> Fx<S, A>
Parameters
initial: Initial accumulatorf: Accumulator functionstream: Source stream
Example
runFx (fold 0 (acc: x: pure (acc + x)) (fromList [1 2 3]))
# => 6
See Also
toList- Collect to listforEach- Execute for side effects
forEach
Executes an effect for each stream element.
Runs side effects while consuming stream. Returns unit. The effect can access and modify context.
Type Signature
(V -> Fx<S, {}>) -> Stream<S, V> -> Fx<S, {}>
Parameters
f: Effect to executestream: Source stream
Example
# Print each element (conceptually)
runFx (forEach (x: state.modify (s: s + x)) stream)
See Also
fold- Reduce with accumulatormap- Transform without consuming
toList
Collects all stream elements to a list.
Forces entire stream evaluation and gathers results. Be careful with infinite streams!
Type Signature
Stream<S, V> -> Fx<S, [V]>
Parameters
stream: Source stream
Example
runFx (toList (fromList [1 2 3])) # => [1 2 3]
See Also
fromList- Convert from listfold- Custom reduction
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-reduce.nix
stream-stream-combine.nix
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-combine.nix
Module Description
Stream combination operations - concatenating, interleaving, and zipping streams
Combinators
concat
Concatenates two streams.
Yields all elements from first stream, then all from second. Second stream is not evaluated until first completes.
Type Signature
Stream<S, V> -> Stream<S, V> -> Stream<S, V>
Parameters
s1: First streams2: Second stream
Example
runFx (toList (concat (fromList [1 2]) (fromList [3 4])))
# => [1 2 3 4]
See Also
flatten- Concatenate stream of streamszip- Combine elements pairwise
flatMap
Maps each element to a stream and flattens.
Powerful combinator for complex stream transformations. Each element can produce zero or more output elements.
Type Signature
(V -> Stream<S, U>) -> Stream<S, V> -> Stream<S, U>
Parameters
f: Function producing streamstream: Source stream
Example
runFx (toList (flatMap (x: fromList [x x]) (fromList [1 2])))
# => [1 1 2 2]
See Also
map- Transform valuesflatten- Flatten without mapping
flatten
Flattens a stream of streams into a single stream.
Concatenates all inner streams in order. Useful after mapping operations that produce streams.
Type Signature
Stream<S, Stream<S, V>> -> Stream<S, V>
Parameters
stream: Stream of streams
Example
runFx (toList (flatten (fromList [
fromList [1 2]
fromList [3 4]
]))) # => [1 2 3 4]
See Also
flatMap- Map and flattenconcat- Join two streamsinterleave- Fair stream combination
interleave
Fair interleaving of two streams (miniKanren-style mplus).
Alternates between streams for complete search. Unlike concat
which exhausts first stream before trying second, interleave
swaps streams at each step ensuring fairness.
Essential for logic programming where infinite streams must be explored fairly.
Type Signature
Stream<S, V> -> Stream<S, V> -> Stream<S, V>
Parameters
s1: First streams2: Second stream
Example
# With concat, infinite stream blocks second
# With interleave, both explored fairly
runFx (take 6 (interleave
(fromList [1 2 3])
(fromList [10 20 30])))
# => [1 10 2 20 3 30]
See Also
concat- Unfair concatenation (exhausts first)flatten- For stream of streams- Logic programming: mplus (OR) operation
zip
Zips two streams into pairs.
Combines elements pairwise. Terminates when either stream ends.
Type Signature
Stream<S, A> -> Stream<S, B> -> Stream<S, {fst: A, snd: B}>
Parameters
s1: First streams2: Second stream
Example
runFx (toList (zip (fromList [1 2]) (fromList ["a" "b"])))
# => [{fst=1; snd="a";} {fst=2; snd="b";}]
See Also
pair.make- Create pairsconcat- Sequential combination
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/stream-combine.nix
conditions
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/conditions.nix
Module Description
Common Lisp style condition system for resumable error handling.
The condition system provides signaling, handling, and restart mechanisms that go beyond simple exceptions. Key features:
- Conditions - Signals that can be handled without unwinding
- Handlers - Dynamic scoped responders to conditions
- Restarts - Named recovery strategies available at signal site
- Resumption - Continue execution after handling (not just unwind)
Condition System Flow
- Code signals a condition with available restarts
- Handler examines condition and chooses a restart
- Restart continues execution from signal point (or unwinds)
Example
# Define function with restarts
parseConfig = file:
withRestart "use-default" (dflt: pure dflt)
(withRestart "retry" (_: parseConfig file)
(map (_: throw "Parse failed")
(signal { type = "parse-error"; file = file; })));
# Handle with restart selection
parsed = runFx (
handle "parse-error" (cond:
if canRecover cond.file
then invokeRestart "use-default" defaultConfig
else invokeRestart "retry" {})
(parseConfig "config.json")
);
Comparison to Exceptions
| Feature | Exceptions | Conditions |
|---|---|---|
| Signaling | throw | signal |
| Handling | catch (unwinds) | handle (can resume) |
| Recovery | return value | invoke restart |
| Stack | Unwound | Preserved (if resuming) |
See Also
- Common Lisp: CLHS 9 (Conditions)
- Kent Pitman’s “Condition System” paper
Combinators
cerror
Signals a continuable error with a default restart.
Convenience for errors that have a sensible way to continue. Automatically defines a “continue” restart that returns the provided default value.
Type Signature
String -> V -> String -> Attrset -> Fx<S, V>
Parameters
continueMessage: Message shown for continue optiondefaultValue: Value if continue chosenerrorMessage: Error descriptiondetails: Error details
Example
cerror "Use default config" defaultConfig
"Config parse failed" { file = "config.json"; }
# Handler can:
# - invokeRestart "continue" {} -> returns defaultConfig
# - invokeRestart "abort" cond -> aborts
See Also
error- Non-continuable errorwithRestart- Manual restart definition
error
Signals a non-resumable error condition.
Convenience function for signaling errors. Unlike general conditions, errors are not meant to be resumed from. Handlers should invoke a restart (typically “abort”) rather than returning a value.
Type Signature
String -> Attrset -> Fx<S, V>
Parameters
message: Error messagedetails: Additional error details
Example
error "File not found" { file = "config.json"; }
# Handler must invoke restart:
handle "error" (cond:
invokeRestart "abort" cond
) code
See Also
signal- General condition signalingcerror- Continuable errorwarn- Non-error condition
findRestart
Checks if a restart is available.
Searches the restart stack without invoking. Useful for handlers that want to check available recovery options.
Type Signature
String -> Fx<{restarts: [Restart]}, Bool>
Parameters
name: Restart name to find
Example
func (ctx:
if findRestart "retry" ctx
then invokeRestart "retry" {}
else invokeRestart "abort" {}
)
See Also
invokeRestart- Invoke restartlistRestarts- List all available
handle
Establishes a handler for conditions of given type.
Handlers are dynamically scoped - they apply to all conditions signaled during the effect’s execution. Handlers are checked from innermost to outermost.
Type Signature
String -> (Condition -> Fx<S, V>) -> Fx<S, V> -> Fx<S, V>
Parameters
conditionType: Type of condition to handle (“*” matches all)handler: Function receiving condition, returns effecteffect: Effect to protect with handler
Example
handle "parse-error" (cond:
# Can invoke restart, return value, or signal
invokeRestart "use-default" defaultConfig
) (
parseFile "config.json"
)
Handler Actions
The handler can:
invokeRestart name value- Resume at signal pointpure value- Provide value (if condition resumable)signal otherCondition- Chain handling- Decline by signaling
{ type = "decline"; }
See Also
signal- Signal conditionswithRestart- Define restartshandleBind- Multiple handlers
handleBind
Establishes multiple handlers at once.
Convenience for binding several handlers in one scope.
Equivalent to nested handle calls but more concise.
Type Signature
[{pattern: String, action: Handler}] -> Fx<S, V> -> Fx<S, V>
Parameters
bindings: List of {pattern, action} handlerseffect: Protected effect
Example
handleBind [
{ pattern = "error"; action = cond: invokeRestart "abort" cond; }
{ pattern = "warning"; action = cond: logWarning cond; }
] code
See Also
handle- Single handlersignal- Condition signaling
ignoreErrors
Ignores all error conditions, returning default value.
Convenience handler that catches all errors and provides a fallback value. Useful for optional operations.
Type Signature
V -> Fx<S, V> -> Fx<S, V>
Parameters
default: Value to return on any erroreffect: Effect that might error
Example
ignoreErrors {} (
parseConfig "optional.json"
) # Returns {} if parse fails
See Also
handle- Conditional handlingcerror- Continuable errors
invokeRestart
Finds and invokes a restart by name.
Searches the dynamic restart stack for a restart with the given name and invokes it with the provided value. This is how handlers resume or recover from conditions.
Type Signature
String -> Value -> Fx<{restarts: [Restart]}, V>
Parameters
name: Name of restart to invokevalue: Value to pass to restart action
Example
handle "parse-error" (cond:
if recoverable cond
then invokeRestart "use-default" defaultConfig
else invokeRestart "abort" { error = cond; }
) protectedCode
Behavior
- Searches restarts innermost to outermost
- Throws if restart not found
- Invokes restart action with value
- Control transfers to restart point
See Also
withRestart- Define restartsrestart- Direct invocationfindRestart- Check restart availability
restart
Direct restart invocation (for use within signal context).
Lower-level primitive for invoking restarts. Typically used within handler code when the restart is known to be available.
Type Signature
String -> Value -> Fx<S, V>
Parameters
name: Restart namevalue: Value for restart
Example
handle "error" (cond:
restart "abort" { error = cond; }
) code
See Also
invokeRestart- Recommended for general usewithRestart- Define restarts
signal
Signals a condition, requesting handler from context.
Unlike exceptions that unwind the stack, signaling a condition requests a handler without unwinding. The handler can:
- Invoke a restart to resume
- Return a value
- Signal another condition
- Decline (no match), bubbling to outer handlers
Type Signature
Condition -> Fx<{handlers: [Handler], restarts: [Restart]}, {}>
Parameters
condition: Attrset describing the conditiontype: String identifying condition type (required)- Other fields provide context
Example
# Signal parse error
signal {
type = "parse-error";
file = "config.json";
line = 42;
}
# Handler will be invoked without unwinding
Notes
- Signal itself returns unit after handler completes
- To abort with error, handler must invoke abort restart
- Multiple handlers can be established (innermost first)
See Also
handle- Establish handlerwithRestart- Define recovery optionserror- Signal non-resumable error
warn
Signals a warning condition.
Warnings are informational conditions that don’t require recovery. By default, they are ignored (resumable), but handlers can log, collect, or promote them to errors.
Type Signature
String -> Attrset -> Fx<S, {}>
Parameters
message: Warning messagedetails: Additional context
Example
warn "Deprecated option" { option = "oldName"; }
# Handler can log or collect:
handle "warning" (cond:
trace cond.message (pure {})
) code
See Also
signal- General signalingerror- Error conditions
withRestart
Defines a named restart available at this scope.
Restarts are recovery strategies offered by the code that signals. Handlers can invoke restarts to resume or recover from conditions. Multiple restarts can be defined, creating a menu of options.
Type Signature
String -> (Value -> Fx<S, V>) -> Fx<S, V> -> Fx<S, V>
Parameters
name: Restart name (e.g., “retry”, “use-default”, “abort”)action: Function invoked when restart choseneffect: Effect protected by this restart
Example
withRestart "use-default" (dflt: pure dflt)
(withRestart "retry" (_: tryAgain)
(parseFile "config.json"))
Common Restart Names
abort- Abandon operation, return errorretry- Try operation againuse-value- Use provided value insteaduse-default- Use default valueskip- Skip problematic operationcontinue- Proceed despite warning
See Also
invokeRestart- Invoke by namerestart- Direct restart invocationsignal- Signals that trigger restarts
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/conditions.nix
result
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/result.nix
Module Description
Simple Result-based error handling built on condition system.
Provides familiar throw/catch semantics as a convenience layer over the more powerful condition system. Unlike conditions, Results always unwind the stack on error.
Comparison
| Result | Conditions |
|---|---|
| throw’/catch’ | signal/handle |
| Always unwinds | Can resume |
| Simple | Powerful |
| One handler wins | Multiple handlers |
Example
result = catch' (
divide = x: y:
if y == 0
then throw' "DivideByZero" { dividend = x; }
else pure (x / y);
divide 10 2
);
# => Ok 5
result2 = catch' (divide 10 0);
# => Err { type = "DivideByZero"; dividend = 10; }
When to Use
- Use Result for simple error propagation
- Use Conditions when you need resumption or multiple handlers
Combinators
bindResult
Chain Result-producing operations.
If the Result is successful, applies the function to the value. Otherwise passes the error through.
Type Signature
(A -> Result<B>) -> Result<A> -> Result<B>
Parameters
f: Function returning a Resultresult: Input Result
Example
validateAge = age:
if age < 0 then { success = false; error = "negative"; }
else { success = true; value = age; };
bindResult validateAge { success = true; value = 25; }
# => { success = true; value = 25; }
catch'
Catch errors thrown with throw’.
Wraps an effect to catch any thrown errors and return them as Result values: { success = true; value = v; } for success or { success = false; error = e; } for errors.
Type Signature
Fx<S, V> -> Fx<S, Result<V>>
Parameters
effect: Effect that may throw errors
Returns
Result with either:
{ success = true; value = V; }{ success = false; error = ErrorDetails; }
Example
result = catch' (
bind (pure 10) (x:
if x > 5
then throw' "TooBig" { value = x; }
else pure x
)
);
# => { success = false; error = { type = "TooBig"; value = 10; }; }
See Also
throw'- Throw an errortry- Catch with default value
mapResult
Transform the value inside a successful Result.
Applies a function to the value if the Result is successful, otherwise passes the error through unchanged.
Type Signature
(A -> B) -> Result<A> -> Result<B>
Parameters
f: Function to apply to successful valueresult: Result to transform
Example
mapResult (x: x * 2) { success = true; value = 21; }
# => { success = true; value = 42; }
mapResult (x: x * 2) { success = false; error = {...}; }
# => { success = false; error = {...}; }
throw'
Throw an error that unwinds the stack.
Signals an error condition that cannot be resumed. The error will propagate up to the nearest catch’ handler.
Type Signature
String -> Attrs -> Fx<S, never>
Parameters
errorType: Error type identifierdetails: Additional error information
Example
validateAge = age:
if age < 0
then throw' "InvalidAge" { age = age; }
else pure age;
See Also
catch'- Handle thrown errorstry- Catch with default valueerror- Non-resumable condition system error
try
Try an effect, returning a default value on error.
Convenience wrapper around catch’ that extracts the value or returns the default on error.
Type Signature
V -> Fx<S, V> -> Fx<S, V>
Parameters
default: Value to return if effect throwseffect: Effect to try
Example
result = try 0 (
if somethingWrong
then throw' "Failed" {}
else pure 42
);
# => 42 on success, 0 on error
See Also
catch'- Catch and inspect errorthrow'- Throw an error
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/result.nix
rw
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/rw.nix
Module Description
Reader and Writer effects built on existing primitives.
This module provides clean APIs for two common effect patterns:
- Reader: Read-only environment access (built on state.get + provide)
- Writer: Append-only output accumulation (built on acc)
Reader Pattern
Reader provides access to immutable environment/configuration without
explicit parameter threading. It’s just state.get with nicer names.
Writer Pattern
Writer accumulates output (logs, events, metadata) alongside computation.
It’s just acc with monoid semantics and cleaner API.
Example
# Reader: configuration access
runFx (runReader { debug = true; timeout = 30; } (
asks (cfg: cfg.debug)
)) # => true
# Writer: logging
runFx (runWriter (
then' (pure 42) (
then' (tell "Done") (tell "Starting")
)
)) # => { value = 42; output = ["Starting" "Done"]; }
Combinators
ask
Reads the entire Reader environment.
Retrieves the complete environment value that was provided via
runReader. This is just state.get with a more semantic name
for read-only environment access.
Type Signature
Fx<Env, Env>
Example
runFx (runReader { x = 1; y = 2; } (
map (env: env.x + env.y) ask
)) # => 3
See Also
asks- Read with projectionrunReader- Provide environment
asks
Reads environment with a projection function.
Retrieves a computed value from the environment by applying a function. Useful for extracting specific fields or deriving values from the environment.
Type Signature
(Env -> A) -> Fx<Env, A>
Parameters
f: Projection function from environment to desired value
Example
runFx (runReader { port = 8080; host = "localhost"; } (
asks (env: env.host + ":" + toString env.port)
)) # => "localhost:8080"
See Also
ask- Read entire environmentlocal- Modify environment locally
censor
Transforms the accumulated output of an effect.
Runs an effect with output accumulation, then applies a transformation to the collected output before returning. The effect’s value is unchanged.
Type Signature
([A] -> [B]) -> Fx<{acc: [A]}, V> -> Fx<{}, {value: V, output: [B]}>
Parameters
f: Function to transform the accumulated outpute: Effect to execute
Example
runFx (censor (output: map toUpper output) (
then' (pure 42) (
then' (tell "world") (tell "hello")
)
)) # => { value = 42; output = ["HELLO" "WORLD"]; }
See Also
tell- Write to outputlisten- Capture output
execWriter
Executes a Writer effect and extracts only the accumulated output.
Like runWriter but discards the computed value, returning only
the accumulated output. Useful when the accumulation is the goal.
Type Signature
Fx<{acc: [A], state: S}, V> -> Fx<S, [A]>
Parameters
e: Writer effect to execute
Returns
List of all accumulated values from tell calls
Example
runFx (execWriter (
then' (pure "ignored") (
then' (tell "event3") (
then' (tell "event2") (tell "event1")
)
)
)) # => ["event1" "event2" "event3"]
See Also
runWriter- Extract both value and outputtell- Write to output
listen
Runs an effect and captures its accumulated output.
Executes an effect while collecting all tell calls into an
output list. Returns both the effect’s value and the accumulated
output.
Type Signature
Fx<{acc: [A], state: S}, V> -> Fx<S, {value: V, output: [A]}>
Parameters
e: Effect to execute with output capturing
Returns
{value: V, output: [A]} where output contains all tell values
Example
runFx (listen (
then' (pure 42) (
then' (tell "log2") (tell "log1")
)
)) # => { value = 42; output = ["log1" "log2"]; }
See Also
tell- Write to outputcensor- Transform output
listens
Like listen but applies a projection to the captured output.
Executes an effect with output capturing, applies a function to transform the output, and returns both the value and transformed output.
Type Signature
([A] -> B) -> Fx<{acc: [A]}, V> -> Fx<{}, {value: V, output: B}>
Parameters
f: Function to transform captured outpute: Effect to execute
Example
runFx (listens (output: length output) (
then' (pure 42) (
then' (tell "b") (tell "a")
)
)) # => { value = 42; output = 2; }
See Also
listen- Capture output as-iscensor- Transform output before returning
local
Runs an effect with a modified environment.
Executes an effect with a locally transformed environment, without affecting the outer environment. The transformation only applies to the inner effect.
Type Signature
(Env -> Env) -> Fx<Env, V> -> Fx<Env, V>
Parameters
f: Function to transform the environmente: Effect to run with modified environment
Example
runFx (runReader { debug = false; } (
local (env: env // { debug = true; }) (
asks (env: env.debug)
)
)) # => true (outer remains false)
See Also
ask- Read environmentrunReader- Provide initial environment
pass
Runs an effect that returns both a value and an output transformer.
Advanced Writer combinator that allows the effect to specify how its own output should be transformed. The effect returns a pair of (value, output-transformer-function).
Type Signature
Fx<{acc: [A]}, (V, [A] -> [B])> -> Fx<{}, {value: V, output: [B]}>
Parameters
e: Effect returning (value, transformation-function)
Example
runFx (pass (
then' (pure {
value = 42;
transform = output: map toUpper output;
}) (tell "raw")
)) # => { value = 42; output = ["RAW"]; }
See Also
censor- Simpler output transformationlisten- Capture output
runReader
Provides an environment for Reader effects.
Supplies the environment that ask and asks will read.
This is just provide with a semantic name for Reader pattern.
Type Signature
Env -> Fx<Env, V> -> Fx<{}, V>
Parameters
env: Environment value to providee: Effect requiring environment
Example
runFx (runReader { apiKey = "secret"; baseUrl = "api.example.com"; } (
asks (env: fetchUrl env.baseUrl env.apiKey)
))
See Also
ask- Read environmentasks- Read with projection
runWriter
Executes a Writer effect and extracts both value and output.
Runs an effect that uses tell to accumulate output, returning
both the computed value and all accumulated output.
Type Signature
Fx<{acc: [A], state: S}, V> -> Fx<S, {value: V, output: [A]}>
Parameters
e: Writer effect to execute
Returns
{value: V, output: [A]} containing result and accumulated output
Example
runFx (runWriter (
mapM (verbose:
if verbose
then then' (pure "OK") (tell "Verbose mode")
else pure "OK"
) (asks (cfg: cfg.verbose))
))
See Also
execWriter- Extract only outputtell- Write to output
tell
Appends a value to the Writer output.
Accumulates a value in the Writer’s output list. The value is appended to the current accumulated output without affecting the computation’s result.
Type Signature
A -> Fx<{acc: [A], state: S}, {}>
Parameters
value: Value to append to output
Example
runFx (runWriter (
then' (pure 42) (
then' (tell "step2") (tell "step1")
)
)) # => { value = 42; output = ["step1" "step2"]; }
See Also
listen- Capture outputrunWriter- Execute and extract output
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/rw.nix
choice
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/choice.nix
Module Description
Logic programming and non-deterministic choice combinators.
Built on streams (interleave/done/flatMap), this module provides miniKanren-style combinators for logic programming, backtracking, and exploring multiple solution paths fairly.
Core Concepts
- mzero: Empty/failure (no solutions) = stream.done
- mplus: Fair choice/OR = stream.interleave
- mprod: Conjunction/AND = stream.flatMap
Choice effects return streams of solutions. Use observe to extract
the first solution, or observeAll to collect all solutions.
Example
# Try multiple options, first success wins
runFx (observe (
orElse
(if false then pure 1 else mzero)
(pure 2)
)) # => 2
# Generate multiple solutions
runFx (observeAll (
choice [
(pure 1)
(pure 2)
(pure 3)
]
)) # => [1 2 3]
# Conditional choice with guard
numberBetween = n:
flatMap (x:
mapM (_: guard (x >= 1 && x <= n)) (pure x)
) (choice (map pure (range 1 10)));
Namespace Contents
mzero- Failure/no solutionsmplus- Fair binary choice (try both)orElse- Try first, fallback to second on failurechoice- First successful from listguard- Conditional continuationobserve- Extract first solutionobserveAll- Collect all solutionsifte- If-then-else for logiconce- At most one solution
Combinators
choice
N-ary choice - select from list of alternatives.
Tries each alternative in order (fairly interleaved). Returns stream of all solutions from all branches. Empty list produces mzero.
Type Signature
[Fx<S, Stream<S, V>>] -> Fx<S, Stream<S, V>>
Parameters
alternatives: List of effects to try
Example
runFx (observeAll (
choice [
(pure 1)
(pure 2)
(pure 3)
]
)) # => [1 2 3]
# Empty choice = failure
runFx (observe (choice [])) # => null
See Also
orElse- Binary choicemplus- Fair binary combination
guard
Conditional continuation - succeed if condition holds.
If the predicate is true, continue with computation. Otherwise, fail (produce mzero). Common in logic programming for pruning invalid solution paths.
Type Signature
Bool -> Fx<{}, Stream<{}, {}>>
Parameters
cond: Boolean condition
Example
# Filter solutions
validNumbers = flatMap (n:
mapM (_: pure n) (guard (n > 0 && n < 10))
) allNumbers;
See Also
mzero- Unconditional failure- Logic programming: constraint satisfaction
ifte
If-then-else for logic programming.
Tests a condition effect. If it produces at least one solution, runs the ‘then’ branch with that solution. Otherwise runs the ‘else’ branch.
Type Signature
Fx<S, Stream<S, V>> -> (V -> Fx<S, Stream<S, U>>) -> Fx<S, Stream<S, U>> -> Fx<S, Stream<S, U>>
Parameters
cond: Condition to testthenBranch: Function applied to first solution if condition succeedselseBranch: Executed if condition produces no solutions
Example
ifte
(guard (x > 0))
(_: pure "positive")
(pure "non-positive")
See Also
orElse- Simpler fallback patternonce- Take first solution
mplus
Fair binary choice - combines two alternatives.
miniKanren-style mplus that fairly interleaves solutions from both branches. Essential for complete search over infinite solution spaces.
Type Signature
Stream<S, V> -> Stream<S, V> -> Stream<S, V>
Parameters
s1: First alternatives2: Second alternative
Example
runFx (observeAll (
mplus
(pure 1)
(pure 2)
)) # => [1 2]
See Also
orElse- For non-stream effectschoice- N-ary choice- Logic programming: fair disjunction (OR)
mzero
Empty choice / failure - yields no solutions.
Represents a computation that fails or has no valid results. Identity element for mplus (choice).
Type Signature
Stream<{}, V> (for any V)
Example
runFx (observe mzero) # => null (no solution)
runFx (observe (mplus mzero (pure 42))) # => 42
See Also
mplus- Combine alternativesguard- Conditional failure
observe
Extract the first solution from a choice computation.
Runs the effect and returns the first value from the result stream, or null if no solutions exist. Use this to “commit” to the first successful branch.
Type Signature
Fx<S, Stream<S, V>> -> Fx<S, V | null>
Parameters
e: Choice effect
Example
runFx (observe (
choice [
mzero
(pure 42)
(pure 99)
]
)) # => 42 (first success)
See Also
observeAll- Collect all solutionsonce- At most one solution
observeAll
Collect all solutions from a choice computation.
Runs the effect and collects all values from the result stream into a list. Use this to explore the complete solution space.
Type Signature
Fx<S, Stream<S, V>> -> Fx<S, [V]>
Parameters
e: Choice effect
Example
runFx (observeAll (
choice [
(pure 1)
(pure 2)
(pure 3)
]
)) # => [1 2 3]
See Also
observe- Just first solution- Logic programming: solution enumeration
once
At most one solution - commits to first success.
Runs the effect but takes only the first solution if any exists. Useful for pruning the search space when you don’t need all alternatives.
Type Signature
Fx<S, Stream<S, V>> -> Fx<S, Stream<S, V>>
Parameters
e: Effect to limit
Example
runFx (observeAll (
once (
choice [
(pure 1)
(pure 2)
(pure 3)
]
)
)) # => [1] (only first)
See Also
observe- Extract first (doesn’t return stream)ifte- Conditional based on first solution
orElse
Try first effect, fallback to second on failure.
Attempts the first computation. If it produces no solutions (empty stream), tries the second. More efficient than mplus when you only need the first success.
Type Signature
Fx<S, Stream<S, V>> -> Fx<S, Stream<S, V>> -> Fx<S, Stream<S, V>>
Parameters
e1: Primary effecte2: Fallback effect
Example
divide = x: y:
orElse
(if y != 0 then pure (x / y) else mzero)
(pure 0); # fallback value
See Also
mplus- Fair interleavingchoice- Multiple alternatives
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/choice.nix
bracket
Source: /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/bracket.nix
Module Description
Resource management with acquire/release patterns.
Ensures cleanup code runs even when errors occur. Essential for managing resources like file handles, connections, or locks that must be properly released.
Built on the condition system for error handling.
Core Pattern
bracket
acquire # Fx<S, Resource>
release # Resource -> Fx<S, {}>
use # Resource -> Fx<S, Value>
The release function ALWAYS runs, even on error.
Example
# Acquire file handle, ensure it closes
withFile = path: action:
bracket
(openFile path) # acquire
(handle: closeFile handle) # release (always runs)
action; # use
result = runFx (withFile "data.txt" (handle:
readContents handle
));
Namespace Contents
bracket- Acquire/release/use patternbracket_- Ignore result, return use valuefinally- Ensure action runs after effectonError- Run action only on erroronSuccess- Run action only on successbracketOnError- Release only on error
Combinators
bracket
General acquire/release/use pattern.
Acquires a resource, runs a computation with it, and ensures the resource is released regardless of success or failure. Returns both the computation result and release result.
Type Signature
Fx<S, R> -> (R -> Fx<S, C>) -> (R -> Fx<S, V>) -> Fx<S, {value: V, cleanup: C}>
Parameters
acquire: Effect that acquires resourcerelease: Function to release resource (always runs)use: Function to use resource
Example
bracket
(openConnection "db.sqlite")
(conn: closeConnection conn)
(conn: query conn "SELECT * FROM users")
# => { value = queryResult; cleanup = {}; }
See Also
bracket_- Simpler version that discards cleanup resultfinally- Ensure action runsbracketOnError- Release only on error
bracketOnError
Acquire/release pattern that only releases on error.
Like bracket but cleanup only happens if use fails.
On success, the resource is left acquired (caller’s responsibility).
Type Signature
Fx<S, R> -> (R -> Fx<S, {}>) -> (R -> Fx<S, V>) -> Fx<S, V>
Parameters
acquire: Effect that acquires resourcerelease: Function to release on error onlyuse: Function to use resource
Example
bracketOnError
(beginTransaction)
(_: rollback)
(tx:
do [
(_: insertUser tx user)
(_: insertPosts tx posts)
(_: commit tx) # Success: we committed
])
# rollback only runs if insertUser/insertPosts fail
See Also
bracket- Always releasesonError- Simpler error-only action
bracket_
Simplified bracket that discards release result.
Like bracket but only returns the use result, discarding
the cleanup value. Most common case for resource management.
Type Signature
Fx<S, R> -> (R -> Fx<S, {}>) -> (R -> Fx<S, V>) -> Fx<S, V>
Parameters
acquire: Effect that acquires resourcerelease: Function to release resourceuse: Function to use resource
Example
withFile = path: action:
bracket_
(openFile path)
(h: closeFile h)
action;
content = runFx (withFile "data.txt" readAll);
See Also
bracket- Full version with cleanup resultfinally- Simpler cleanup without resource
finally
Ensures an action runs after an effect, even on error.
Simpler than bracket when you don’t need to acquire/pass a resource. The cleanup action runs regardless of success or failure.
Type Signature
Fx<S, V> -> Fx<S, {}> -> Fx<S, V>
Parameters
effect: Main computationcleanup: Action to run afterwards (always)
Example
finally
(riskyComputation)
(logMetrics)
# logMetrics runs whether riskyComputation succeeds or fails
See Also
bracket- When you need acquire/releaseonError- Run only on failureonSuccess- Run only on success
onError
Runs an action only if the effect fails.
Error-specific cleanup or logging. The action runs before the error propagates. Original error is preserved.
Type Signature
Fx<S, V> -> Fx<S, {}> -> Fx<S, V>
Parameters
effect: Computation that might failcleanup: Action to run on error only
Example
onError
(riskyOperation)
(rollbackTransaction)
# rollbackTransaction only runs if riskyOperation fails
See Also
onSuccess- Opposite patternfinally- Run on both success and failurebracketOnError- Release resource only on error
onSuccess
Runs an action only if the effect succeeds.
Success-specific actions like committing transactions or sending notifications. The action runs after success, before returning the value.
Type Signature
Fx<S, V> -> Fx<S, {}> -> Fx<S, V>
Parameters
effect: Computation that might succeedaction: Action to run on success only
Example
onSuccess
(transaction)
(commitToDatabase)
# commitToDatabase only runs if transaction succeeds
See Also
onError- Opposite patternfinally- Run on both success and failure
Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/bracket.nix