Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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:

  1. Contravariant mapping of context requirements (what the effect needs)
  2. 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 transform
  • cmap: Context mapper T -> S - extracts inner requirement from outer context
  • fmap: Continuation (T, S, V) -> Fx<T,U> - transforms the result

How It Works

  1. Creates a pending effect expecting context T
  2. Applies cmap to get the inner context S
  3. If effect is immediate, applies fmap to produce final result
  4. 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 value
  • value: 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 computations
  • runFx - 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 function context -> 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 value
  • adapt - 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 evaluation
  • pure - 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 type
  • immediate - 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 empty
  • func - 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 outer Outer -> Inner
  • setter: Updates outer context given new inner state Outer -> Inner -> Outer
  • e: Effect requiring Inner

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 contraMap
  • lens.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 function V -> U
  • e: 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 effect
  • contraMap - 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 version
  • flatMap - 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 context
  • e: 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 sequencing
  • andThen - 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 effect V -> 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 context
  • then' - 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 value
  • andThen - 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 transformation
  • map - 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 provide
  • e: Effect that requires context S

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 context
  • providePart - 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 component
  • e: Effect requiring paired context

Example

provide 20 (
  provideLeft 10
    (pending (ctx: immediate ctx (ctx.fst + ctx.snd)))
)  # => 30

See Also

  • provide - Provides entire context
  • andNil - 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 context
  • cmap: Combines A and remaining context B to form full context S
  • fmap: Extracts remaining context from result state
  • e: Effect requiring full context S

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 provision
  • provideLeft - 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 binding
  • mapM - Single monadic bind
  • then' - 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 binding
  • then' - 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 state
  • set - Replaces the state with a new value
  • modify - Transforms state with a pure function
  • modifyM - 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 access
  • context - 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 context
  • name: Name of the attribute to extract

Example

has { x = 42; y = 1; } "x"  # => 42

See Also

  • put - Updates an attribute in context
  • lift - 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 context
  • e: 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:

  1. Extract the named attribute for the inner effect
  2. Update the named attribute with any state changes

See Also

  • contraMap - Lower-level context transformation
  • lens.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 attrset
  • name: Name of the attribute to update
  • value: 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 context
  • state.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 effects
  • e: 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 handlers
  • provide - 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 part
  • set : 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 transformation
  • lift - 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 A
  • inner: 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 lenses
  • zoomOut - 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 effects
  • compose - 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 component
  • pair.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 structure
  • set: 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 access
  • compose - Combine lenses

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 component
  • pair.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 A
  • inner: Continuation producing effect from A
  • e: 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 effects
  • mapM - 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 A
  • e: 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 continuations
  • contraMap - 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 requirements
  • andSwap, 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 operation
  • fwd - 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 component
  • make - 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 component
  • b: 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 components
  • swap - 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 component
  • make - 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 swap
  • fwd - 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 invoke
  • input: Input to pass to the ability

Example

runFx (
  provide { double = x: pure (x * 2); }
    (request "double" 21)
)  # => 42

How It Works

  1. Creates a pending effect
  2. When evaluated, extracts the ability from context by name
  3. Calls the ability with the input
  4. 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 context
  • provide - 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 (provides snd)
  • e: First effect (provides fst)

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 value
  • zipRight - 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 values
  • zipRight - Keeps second value
  • then' - 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 values
  • zipLeft - 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 function
  • request - Requests an arrow by name and applies it
  • adapt - 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 abilities
  • func - 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 arrow
  • i: 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 outputs
  • contraMap - 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 context
  • adapt - 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 context
  • i: Input value

Example

runFx (
  provide {double = arrow.new (x: x * 2);} (
    arrow.request "double" 21
  )
)  # => 42

See Also

  • new - Create arrows
  • request.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 instead
  • andSwap - 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 operation
  • andCollapse - 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 through
  • state - The actual program state

See Also

  • state - For stateful computations without accumulation
  • mapM - 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 function
  • item: 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 accumulation
  • collect - 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 value
  • e: 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 function
  • withAccumulator - 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 value
  • accFn: Function to accumulate items
  • e: 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 collection
  • option, 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 list
  • item: Item to append

Example

runFx (acc.list [] 1)          # => [1]
runFx (acc.list [1 2] 3)       # => [1 2 3]

See Also

  • collect - Thread list accumulator
  • withAccumulator - 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 accumulation
  • collect - 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 set
  • item: 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 accumulation
  • collectWith - 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 value
  • e: Effect to execute

Example

runFx (withAccumulator [] (
  pending (ctx: immediate {...} 42)
))  # => [items...] (discards 42)

See Also

  • collect - Returns both accumulator and value
  • collectWith - 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 value
  • fromList - 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 list
  • singleton - 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 yield
  • next: Continuation stream (lazy)

Example

more 1 (more 2 (more 3 done))
# Stream of [1, 2, 3]

See Also

  • done - Terminate stream
  • fromList - 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 repeat
  • effect: Effect to execute

Example

runFx (provide 5 (
  toList (repeat 3 state.get)
))  # => [5 5 5]

See Also

  • forEach - Execute for each element
  • map - 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 elements
  • done - 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 function
  • stream: Source stream

Example

runFx (toList (filter (x: x > 2) (fromList [1 2 3 4])))
# => [3 4]

See Also

  • takeWhile - Take until predicate fails
  • map - 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 function
  • stream: Source stream

Example

runFx (toList (map (x: x * 2) (fromList [1 2 3])))
# => [2 4 6]

See Also

  • filter - Select elements
  • flatMap - 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 take
  • stream: Source stream

Example

runFx (toList (take 2 (fromList [1 2 3 4])))
# => [1 2]

See Also

  • takeWhile - Take until condition
  • filter - 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 test
  • stream: Source stream

Example

runFx (toList (takeWhile (x: x < 3) (fromList [1 2 3 4])))
# => [1 2]

See Also

  • take - Take fixed number
  • filter - 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 accumulator
  • f: Accumulator function
  • stream: Source stream

Example

runFx (fold 0 (acc: x: pure (acc + x)) (fromList [1 2 3]))
# => 6

See Also

  • toList - Collect to list
  • forEach - 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 execute
  • stream: Source stream

Example

# Print each element (conceptually)
runFx (forEach (x: state.modify (s: s + x)) stream)

See Also

  • fold - Reduce with accumulator
  • map - 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 list
  • fold - 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 stream
  • s2: Second stream

Example

runFx (toList (concat (fromList [1 2]) (fromList [3 4])))
# => [1 2 3 4]

See Also

  • flatten - Concatenate stream of streams
  • zip - 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 stream
  • stream: Source stream

Example

runFx (toList (flatMap (x: fromList [x x]) (fromList [1 2])))
# => [1 1 2 2]

See Also

  • map - Transform values
  • flatten - 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 flatten
  • concat - Join two streams
  • interleave - 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 stream
  • s2: 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 stream
  • s2: 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 pairs
  • concat - 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

  1. Code signals a condition with available restarts
  2. Handler examines condition and chooses a restart
  3. 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

FeatureExceptionsConditions
Signalingthrowsignal
Handlingcatch (unwinds)handle (can resume)
Recoveryreturn valueinvoke restart
StackUnwoundPreserved (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 option
  • defaultValue: Value if continue chosen
  • errorMessage: Error description
  • details: 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 error
  • withRestart - 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 message
  • details: 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 signaling
  • cerror - Continuable error
  • warn - 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 restart
  • listRestarts - 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 effect
  • effect: 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:

  1. invokeRestart name value - Resume at signal point
  2. pure value - Provide value (if condition resumable)
  3. signal otherCondition - Chain handling
  4. Decline by signaling { type = "decline"; }

See Also

  • signal - Signal conditions
  • withRestart - Define restarts
  • handleBind - 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} handlers
  • effect: Protected effect

Example

handleBind [
  { pattern = "error"; action = cond: invokeRestart "abort" cond; }
  { pattern = "warning"; action = cond: logWarning cond; }
] code

See Also

  • handle - Single handler
  • signal - 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 error
  • effect: Effect that might error

Example

ignoreErrors {} (
  parseConfig "optional.json"
)  # Returns {} if parse fails

See Also

  • handle - Conditional handling
  • cerror - 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 invoke
  • value: 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 restarts
  • restart - Direct invocation
  • findRestart - 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 name
  • value: Value for restart

Example

handle "error" (cond:
  restart "abort" { error = cond; }
) code

See Also

  • invokeRestart - Recommended for general use
  • withRestart - 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 condition
    • type: 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 handler
  • withRestart - Define recovery options
  • error - 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 message
  • details: 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 signaling
  • error - 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 chosen
  • effect: 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 error
  • retry - Try operation again
  • use-value - Use provided value instead
  • use-default - Use default value
  • skip - Skip problematic operation
  • continue - Proceed despite warning

See Also

  • invokeRestart - Invoke by name
  • restart - Direct restart invocation
  • signal - 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

ResultConditions
throw’/catch’signal/handle
Always unwindsCan resume
SimplePowerful
One handler winsMultiple 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 Result
  • result: 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 error
  • try - 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 value
  • result: 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 identifier
  • details: Additional error information

Example

validateAge = age:
  if age < 0
  then throw' "InvalidAge" { age = age; }
  else pure age;

See Also

  • catch' - Handle thrown errors
  • try - Catch with default value
  • error - 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 throws
  • effect: 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 error
  • throw' - 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 projection
  • runReader - 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 environment
  • local - 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 output
  • e: 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 output
  • listen - 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 output
  • tell - 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 output
  • censor - 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 output
  • e: 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-is
  • censor - 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 environment
  • e: 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 environment
  • runReader - 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 transformation
  • listen - 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 provide
  • e: Effect requiring environment

Example

runFx (runReader { apiKey = "secret"; baseUrl = "api.example.com"; } (
  asks (env: fetchUrl env.baseUrl env.apiKey)
))

See Also

  • ask - Read environment
  • asks - 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 output
  • tell - 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 output
  • runWriter - 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 solutions
  • mplus - Fair binary choice (try both)
  • orElse - Try first, fallback to second on failure
  • choice - First successful from list
  • guard - Conditional continuation
  • observe - Extract first solution
  • observeAll - Collect all solutions
  • ifte - If-then-else for logic
  • once - 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 choice
  • mplus - 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 test
  • thenBranch: Function applied to first solution if condition succeeds
  • elseBranch: Executed if condition produces no solutions

Example

ifte
  (guard (x > 0))
  (_: pure "positive")
  (pure "non-positive")

See Also

  • orElse - Simpler fallback pattern
  • once - 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 alternative
  • s2: Second alternative

Example

runFx (observeAll (
  mplus
    (pure 1)
    (pure 2)
))  # => [1 2]

See Also

  • orElse - For non-stream effects
  • choice - 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 alternatives
  • guard - 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 solutions
  • once - 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 effect
  • e2: Fallback effect

Example

divide = x: y:
  orElse
    (if y != 0 then pure (x / y) else mzero)
    (pure 0);  # fallback value

See Also

  • mplus - Fair interleaving
  • choice - 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 pattern
  • bracket_ - Ignore result, return use value
  • finally - Ensure action runs after effect
  • onError - Run action only on error
  • onSuccess - Run action only on success
  • bracketOnError - 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 resource
  • release: 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 result
  • finally - Ensure action runs
  • bracketOnError - 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 resource
  • release: Function to release on error only
  • use: 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 releases
  • onError - 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 resource
  • release: Function to release resource
  • use: 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 result
  • finally - 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 computation
  • cleanup: Action to run afterwards (always)

Example

finally
  (riskyComputation)
  (logMetrics)
# logMetrics runs whether riskyComputation succeeds or fails

See Also

  • bracket - When you need acquire/release
  • onError - Run only on failure
  • onSuccess - 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 fail
  • cleanup: Action to run on error only

Example

onError
  (riskyOperation)
  (rollbackTransaction)
# rollbackTransaction only runs if riskyOperation fails

See Also

  • onSuccess - Opposite pattern
  • finally - Run on both success and failure
  • bracketOnError - 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 succeed
  • action: Action to run on success only

Example

onSuccess
  (transaction)
  (commitToDatabase)
# commitToDatabase only runs if transaction succeeds

See Also

  • onError - Opposite pattern
  • finally - Run on both success and failure

Generated from /nix/store/mls72plk3raskl1r5afh3cl9ik3rn969-source/nix/bracket.nix