Skip to content

Memos and computation expressions

A Memo<'T> (memo { ... } or createMemo) caches a derived value and recomputes on demand only when an upstream dependency changes. Memos are lazy (Status.Uninitialized until first read):

  • .Value (or let! inside another builder) pulls upstream dependencies, recomputes if dirty, and records an observer edge when tracking is open.

  • .Peek returns the last stored value in O(1)O(1) without refreshing or subscribing.

  • untracked { return m.Value } refreshes a stale memo without subscribing (see Signals — Untracked reads).

For well-behaved synchronous graphs, pull verification guarantees glitch-free reads across diamonds,1 and recomputing an equal output cuts off downstream observers2:

Example code
let count = signal { return 1 }
let doubled =
    memo {
        let! n = count
        return n * 2
    }
doubled.Value |> ignore

controls [
    button "Write 5" (fun () -> count.Value <- 5)
    |> describe "Writing count marks doubled stale; no observer pulls it yet."
    |> expect "Unobserved memo stays at stored 2" (fun () -> doubled.Peek = 2 && doubled.Runs = 1)
    button "Peek" (fun () -> printfn "stored = %d" doubled.Peek)
    |> describe "Peek inspects the cached 2 without running doubled."
    |> expect "Peek does not refresh" (fun () -> doubled.Peek = 2 && doubled.Runs = 1)
    button "Read" (fun () -> printfn "current = %d" doubled.Value)
    |> describe "Reading doubled.Value refreshes it to 10."
    |> expect "Read refreshes to 10" (fun () -> doubled.Peek = 10 && doubled.Runs = 2)
]
Hover a node for its state; click it for why it last ran.

Two-phase computation expressions

Open Ranvier and Ranvier.CE to write reactive computations as two-phase blocks:

open Ranvier
open Ranvier.CE

let lineTotal (price: Signal<decimal>) (qty: Signal<int>) =
    memo {
        let! p = price
        and! q = qty
        return p * decimal q
    }

Static let! ... and! ... vs dynamic sequential let!

Static binds

let! a = x and! b = y combines independent IReactive<'T> inputs (Signal, ReadOnlySignal, Memo, Editable, Boundary, AsyncMemo, AsyncSource, StreamMemo, Timed, or pointwise descriptors) into a 0 B struct MergedPair.

  • Graph inference: static binds infer Graph directly from the bound sources without graph.Activate (). See The graph — Graph inference.

  • Tracking: static binds wire fixed edges in O(1)O(1) and close dependency tracking before the Phase-2 return body. Helper calls in that body cannot accidentally subscribe.

  • Cutoff: the Phase-1 input key and the Phase-2 output value each have an equality check.

Dynamic binds

When a second let! depends on the first value, or when control flow branches via if, match!, or for, the computation tracks reads dynamically.3 Untaken branches automatically drop their observer edges at run end4:

Example code
let usePrimary = signal { return true }
let primary = signal { return "alpha" }
let fallback = signal { return "omega" }
let mutable effectRuns = 0

effect {
    let! pickPrimary = usePrimary
    let! chosen = if pickPrimary then primary else fallback
    effectRuns <- effectRuns + 1
    printfn "%s" chosen
}

controls [
    button "Switch to fallback" (fun () -> usePrimary.Value <- false)
    |> expect "Switches active dependency to fallback" (fun () -> effectRuns = 2)
    button "Write primary" (fun () -> primary.Value <- "alpha-2")
    |> expect "Inactive branch write wakes nothing" (fun () -> effectRuns = 2)
    button "Write fallback" (fun () -> fallback.Value <- "omega-2")
    |> expect "Active branch write runs the effect" (fun () -> effectRuns = 3)
]
Hover a node for its state; click it for why it last ran.

Use return! innerMemo inside memo (Signal.bind / Memo.bind) to follow a dynamically selected Memo<'U>; updates to the inner memo propagate without re-running the outer selector while the outer key stays equal.

Previous output, option deduplication, and tryRead

Reuse the previous output

Bind let! prev = memo.previous ('T voption) or let! best = memo.previousOr 0 ('T) to fold running maxima or reuse prior results across runs.

editable.previous*, draft.previous*, and asyncMemo.previous provide the equivalent tokens for their builders:

let runningMax (reading: Signal<int>) =
    memo {
        let! current = reading
        let! best = memo.previousOr System.Int32.MinValue
        return max best current
    }

Reuse an option wrapper

memo { option; let! xs = items; return List.tryFind pred xs }(createOptionMemo) reuses the previous Some heap box whenever its inner payload compares equal, preventing allocations and spurious reference-identity wakes on .NET.

option is mutually exclusive with owning, comparer, and memo.previous*.

Read without suspending

Wrap any ITryReactive<'T> source in tryRead src to bind Reading<'T>(Ready value, Pending, or Failed exn) via .TryValuewithout suspending or faulting:

let badge (req: AsyncMemo<string>) =
    memo {
        match! tryRead req with
        | Ready text -> return text
        | Pending -> return "Loading..."
        | Failed ex -> return $"Error: {ex.Message}"
    }

Pointwise collection reads

Subscribe to individual collection keys or metadata without observing unrelated entries (see Collections and Lookups and selectors):

SourceRequired valueLive optional valueMembership / extra
Projection<'K, 'V>Projection.at key rows ('V)Projection.tryAt key rows ('V option)Projection.keys rows ('K[])
KeyedCollection<'K, 'V>KeyedCollection.at key store ('V)KeyedCollection.tryAt key store ('V option)KeyedCollection.keys store ('K[])
Lookup<'K, 'V>Lookup.at key lkp ('V, creates cell)Lookup.tryAt key lkp ('V option, live cell only)Open key domain
MemoTable<'K, 'V>MemoTable.at key tbl ('V, creates slot)MemoTable.tryAt key tbl ('V voption, live slot only)LRU-bounded open key domain
Editable<'T>Editable.upstream ed ('T)Editable.isEdited ed (bool)Seed vs local override state

Inside Projection.mapWith, createProjectionWith, or createIndexProjectionWith, return row { let! item = readItem and! tag = prefix; return tag + item } (unit -> 'V, 0 extra nodes) to combine per-key row accessors with reactive sources.

Pure and owning memos

By default, memo { ... } (createMemo) runs in ScopeMode.Pure. Creating any owned node (memo, effect, asyncMemo, boundary, root, cleanup, Projection, Lookup) inside its body raises InvalidOperationException, even inside untracked or user try ... with.5

Add the owning header (memo { owning; ... }, or createMemoWith) when a derivation needs to own child nodes or cleanup callbacks:

let sessionView (token: Signal<string>) =
    memo {
        owning
        let! tok = token
        cleanup { printfn "closing %s" tok }
        return $"session:{tok}"
    }
  • Child nodes and cleanups created in an owning memo belong to that run (or to that settled Phase-1 key when using static binds) and tear down in LIFO order before the next run or on Dispose.6

  • Never construct and read an AsyncMemo inside the same owning body (re-running on settle disposes and restarts the flight forever; see Troubleshooting).

  • A disposed Memo<'T> detaches upstream edges and keeps answering reads with its last cached value.7

For bounded LRU payload eviction over large key spaces, use MemoTable<'K, 'V>.

Compute from a settled key

Ranvier.CE separates Phase-1 input key equality from Phase-2 output equality:

  • Input key cutoff (src |> withComparer keyCmp): skips Phase 2 (and preserves any owning scope, running asyncMemo flight, or stream subscription) whenever the bound source — or individual and! arm — settles to a key equal under keyCmp.

  • Output cutoff (comparer outCmp header): compares Phase-2 results under outCmp to suppress downstream observer wakes when recomputation yields an equivalent output.

open System

let searchSummary (rawQuery: Signal<string>) (limit: Signal<int>) =
    let normalized =
        memo {
            let! q = rawQuery
            return q.Trim()
        }

    memo {
        comparer StringComparer.OrdinalIgnoreCase
        let! term = normalized |> withComparer StringComparer.OrdinalIgnoreCase
        and! cap = limit
        return $"Showing {cap} results for '{term}'"
    }

Pre-CE combinators (Signal.map, Signal.map2, Signal.zip, Signal.bind, Memo.map*, AsyncMemo.map*, StreamMemo.map*, createMemoOn*) compile to the same underlying CombinatorMemos and CreateOn nodes.

Unobserved linear map chains sharing an owner fuse automatically on untraced, unjournaled graphs.

See Equality and timing for Phase-1 debounce / throttle* headers and per-arm debounced / throttled* pipes, and Benchmarks → Memos for measured costs.

Computation expression reference

All builders below live in Ranvier.CE (open Ranvier + open Ranvier.CE):

Builder / operatorReturn typeHeaders & context tokensTime & space cost
signal { ... }Signal<'T>comparer cmpO(1)O(1) alloc on Graph.Current; O(1)O(1) read, O(observers)O(\text{observers}) write
memo { ... }Memo<'T>owning, comparer cmp, option; debounce/throttle*, clock c; memo.previous, memo.previousOr seedO(1)O(1) static or dynamic node (0 B MergedPair on and!); lazy pull
memoTable { ... }MemoTable<'K, 'V>maxEntries n or maxWeight w weigh (req.); stamp f + stampComparer c, or comparer c; keyComparer c, maxDormant n, onCycle f, graph g; memoTable.keyO(1)O(1) / 0 B resident hit; O(1)O(1) intrusive LRU eviction
row { ... }unit -> 'VBinds row item thunk + IReactive<'A>0 extra nodes; O(1)O(1) per demanded projection row
effect { ... }unit (INode with node)node; debounce/throttle*, clock cO(1)O(1) Effect / EffectOn registration; runs in flush
bridge target { ... }unit (INode with node)node, comparer cmp; debounce/throttle*, clock cO(1)O(1) source EffectOn + O(1)O(1) / 0 B coalesced SignalPort.Post
dispatch g { ... }unit, Task<unit>, or Task<'T>cancellation ct (or return x for Task<'T>)O(1)O(1) enqueue (O(queued)O(\text{queued}) inbox space); inline on graph thread
asyncMemo { ... }AsyncMemo<'T>owning, policy p, comparer cmp; debounce/throttle*, clock c; asyncMemo.cancellationToken, asyncMemo.previousO(1)O(1) node; pools non-cancelled CancellationTokenSource via TryReset()
stream { ... }StreamMemo<'T> or StreamMemo<'S>fold seed folder; debounce/throttle*, clock c; stream.cancellationTokenO(1)O(1) node; cancels & restarts producer on unequal Phase-1 key
boundary { ... }Boundary<'T>pending fallback and/or failed recover (≥1 req.), comparer cmpO(1)O(1) owning boundary catching Pending / Failed channels
editable { ... }Editable<'T>editable.previous, editable.previousOr seedO(1)O(1) (1 signal + 2 memos); drops local edit on unequal seed
draft { ... }Editable<'T>draft.previous, draft.previousOr seedO(1)O(1) (1 signal + 2 memos); retains local edit until Reset ()
debounced* / throttled*Timed<'T>Pipe on IReactive<'T> (debounced, throttled, throttledFirst, throttledLast + *With)O(1)O(1) per capture; ≤1\le 1 timer (0 timers for throttledFirst*)
root { ... }Owner (or 'T with return)root.ownerO(1)O(1) child scope; O(subtree)O(\text{subtree}) LIFO Dispose ()
owner { ... }'TImplicit CE on Owner (runWithOwner)O(1)O(1) scope swap (0 B)
cleanup { ... }unitNone (onCleanup)O(1)O(1) LIFO registration on current Owner
batched { ... }'TNone (batch)O(1)O(1) depth counter (0 B); flushes effects on outermost exit
untracked { ... }'TNone (untrack)O(1)O(1) tracking suspension (0 B)
graph { ... }'TImplicit CE on Graph (graph.Activate ())O(1)O(1) ambient activation (0 B struct handle)
Edit this page