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(orlet!inside another builder) pulls upstream dependencies, recomputes if dirty, and records an observer edge when tracking is open..Peekreturns the last stored value in 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)
]
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
Graphdirectly from the bound sources withoutgraph.Activate (). See The graph — Graph inference.Tracking: static binds wire fixed edges in and close dependency tracking before the Phase-2
returnbody. 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)
]
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):
| Source | Required value | Live optional value | Membership / 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
owningmemo 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 onDispose.6Never construct and read an
AsyncMemoinside 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 anyowningscope, runningasyncMemoflight, orstreamsubscription) whenever the bound source — or individualand!arm — settles to a key equal underkeyCmp.Output cutoff (
comparer outCmpheader): compares Phase-2 results underoutCmpto 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 / operator | Return type | Headers & context tokens | Time & space cost |
|---|---|---|---|
signal { ... } | Signal<'T> | comparer cmp | alloc on Graph.Current; read, write |
memo { ... } | Memo<'T> | owning, comparer cmp, option; debounce/throttle*, clock c; memo.previous, memo.previousOr seed | 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.key | / 0 B resident hit; intrusive LRU eviction |
row { ... } | unit -> 'V | Binds row item thunk + IReactive<'A> | 0 extra nodes; per demanded projection row |
effect { ... } | unit (INode with node) | node; debounce/throttle*, clock c | Effect / EffectOn registration; runs in flush |
bridge target { ... } | unit (INode with node) | node, comparer cmp; debounce/throttle*, clock c | source EffectOn + / 0 B coalesced SignalPort.Post |
dispatch g { ... } | unit, Task<unit>, or Task<'T> | cancellation ct (or return x for Task<'T>) | enqueue ( inbox space); inline on graph thread |
asyncMemo { ... } | AsyncMemo<'T> | owning, policy p, comparer cmp; debounce/throttle*, clock c; asyncMemo.cancellationToken, asyncMemo.previous | node; pools non-cancelled CancellationTokenSource via TryReset() |
stream { ... } | StreamMemo<'T> or StreamMemo<'S> | fold seed folder; debounce/throttle*, clock c; stream.cancellationToken | node; cancels & restarts producer on unequal Phase-1 key |
boundary { ... } | Boundary<'T> | pending fallback and/or failed recover (≥1 req.), comparer cmp | owning boundary catching Pending / Failed channels |
editable { ... } | Editable<'T> | editable.previous, editable.previousOr seed | (1 signal + 2 memos); drops local edit on unequal seed |
draft { ... } | Editable<'T> | draft.previous, draft.previousOr seed | (1 signal + 2 memos); retains local edit until Reset () |
debounced* / throttled* | Timed<'T> | Pipe on IReactive<'T> (debounced, throttled, throttledFirst, throttledLast + *With) | per capture; timer (0 timers for throttledFirst*) |
root { ... } | Owner (or 'T with return) | root.owner | child scope; LIFO Dispose () |
owner { ... } | 'T | Implicit CE on Owner (runWithOwner) | scope swap (0 B) |
cleanup { ... } | unit | None (onCleanup) | LIFO registration on current Owner |
batched { ... } | 'T | None (batch) | depth counter (0 B); flushes effects on outermost exit |
untracked { ... } | 'T | None (untrack) | tracking suspension (0 B) |
graph { ... } | 'T | Implicit CE on Graph (graph.Activate ()) | ambient activation (0 B struct handle) |