# Memos and computation expressions

> Lazy derived values, two-phase Ranvier.CE binds, pure vs owning scopes, key cutoffs, and the builder reference.

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

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

- `.Peek`{fsharp} returns the last stored value in $O(1)$ without refreshing or subscribing.

- `untracked { return m.Value }`{fsharp} refreshes a stale memo without subscribing (see
  [Signals — Untracked reads](signals.md#untracked-reads)).

For well-behaved synchronous graphs, pull verification guarantees **glitch-free** reads across
diamonds,[^glitch-free] and recomputing an equal output cuts off downstream observers[^cutoff]:

<div class="rv-map-card">

```fsharp
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)
]
```

<div class="rv-map-host" id="rvm-p995eac3051-c1" data-ranvier-map-page="p995eac3051" data-ranvier-map-cell="c1"></div>

</div>


## Two-phase computation expressions

Open `Ranvier`{fsharp} and `Ranvier.CE`{fsharp} to write reactive computations as two-phase
blocks:

```fsharp
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`{fsharp} combines independent `IReactive<'T>`{fsharp} inputs
(`Signal`{fsharp}, `ReadOnlySignal`{fsharp}, `Memo`{fsharp}, `Editable`{fsharp},
`Boundary`{fsharp}, `AsyncMemo`{fsharp}, `AsyncSource`{fsharp}, `StreamMemo`{fsharp},
`Timed`{fsharp}, or pointwise descriptors) into a `0 B` struct `MergedPair`{fsharp}.

- **Graph inference:** static binds infer `Graph`{fsharp} directly from the bound sources without
  `graph.Activate ()`{fsharp}. See [The graph — Graph inference](graph.md#graph-inference).

- **Tracking:** static binds wire fixed edges in $O(1)$ and close dependency tracking before the
  Phase-2 `return`{fsharp} 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!`{fsharp} depends on the first value, or when control flow branches via
`if`{fsharp}, `match!`{fsharp}, or `for`{fsharp}, the computation tracks reads
dynamically.[^latest-reads] Untaken branches automatically drop their observer edges at run
end[^sources-end-run]:

<div class="rv-map-card">

```fsharp
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)
]
```

<div class="rv-map-host" id="rvm-p995eac3051-c2" data-ranvier-map-page="p995eac3051" data-ranvier-map-cell="c2"></div>

</div>


Use `return! innerMemo`{fsharp} inside `memo`{fsharp} (`Signal.bind`{fsharp} /
`Memo.bind`{fsharp}) to follow a dynamically selected `Memo<'U>`{fsharp}; 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`{fsharp} (`'T voption`{fsharp}) or
`let! best = memo.previousOr 0`{fsharp} (`'T`{fsharp}) to fold running maxima or reuse prior
results across runs.

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

```fsharp
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 }`{fsharp}
(`createOptionMemo`{fsharp}) reuses the previous `Some`{fsharp} heap box whenever its inner
payload compares equal, preventing allocations and spurious reference-identity wakes on .NET.

`option`{fsharp} is mutually exclusive with `owning`{fsharp}, `comparer`{fsharp}, and
`memo.previous*`{fsharp}.

#### Read without suspending

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

```fsharp
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](collections.fsx) and [Lookups and selectors](lookups-and-selectors.fsx)):

| Source | Required value | Live optional value | Membership / extra |
| --- | --- | --- | --- |
| `Projection<'K, 'V>`{fsharp} | `Projection.at key rows`{fsharp} (`'V`{fsharp}) | `Projection.tryAt key rows`{fsharp} (`'V option`{fsharp}) | `Projection.keys rows`{fsharp} (`'K[]`{fsharp}) |
| `KeyedCollection<'K, 'V>`{fsharp} | `KeyedCollection.at key store`{fsharp} (`'V`{fsharp}) | `KeyedCollection.tryAt key store`{fsharp} (`'V option`{fsharp}) | `KeyedCollection.keys store`{fsharp} (`'K[]`{fsharp}) |
| `Lookup<'K, 'V>`{fsharp} | `Lookup.at key lkp`{fsharp} (`'V`{fsharp}, creates cell) | `Lookup.tryAt key lkp`{fsharp} (`'V option`{fsharp}, live cell only) | Open key domain |
| `MemoTable<'K, 'V>`{fsharp} | `MemoTable.at key tbl`{fsharp} (`'V`{fsharp}, creates slot) | `MemoTable.tryAt key tbl`{fsharp} (`'V voption`{fsharp}, live slot only) | LRU-bounded open key domain |
| `Editable<'T>`{fsharp} | `Editable.upstream ed`{fsharp} (`'T`{fsharp}) | `Editable.isEdited ed`{fsharp} (`bool`{fsharp}) | Seed vs local override state |

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

## Pure and owning memos

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

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

```fsharp
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`{fsharp} 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`{fsharp}.[^dispose-reverse]

- Never construct and read an `AsyncMemo`{fsharp} inside the same owning body (re-running on
  settle disposes and restarts the flight forever; see [Troubleshooting](troubleshooting.md)).

- A disposed `Memo<'T>`{fsharp} detaches upstream edges and keeps answering reads with its last
  cached value.[^disposed-memo]

For bounded LRU payload eviction over large key spaces, use [`MemoTable<'K, 'V>`](memo-tables.md).

## Compute from a settled key

`Ranvier.CE`{fsharp} separates **Phase-1 input key equality** from **Phase-2 output equality**:

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

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

```fsharp
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`{fsharp}, `Signal.map2`{fsharp}, `Signal.zip`{fsharp},
`Signal.bind`{fsharp}, `Memo.map*`{fsharp}, `AsyncMemo.map*`{fsharp}, `StreamMemo.map*`{fsharp},
`createMemoOn*`{fsharp}) compile to the same underlying `CombinatorMemos`{fsharp} and
`CreateOn`{fsharp} nodes.

Unobserved linear `map`{fsharp} chains sharing an owner fuse automatically on untraced,
unjournaled graphs.

See [Equality and timing](equality-and-timing.md) for Phase-1 `debounce`{fsharp} /
`throttle*`{fsharp} headers and per-arm `debounced`{fsharp} / `throttled*`{fsharp} pipes, and
[Benchmarks → Memos](../benchmarks/memos.md) for measured costs.

## Computation expression reference

All builders below live in `Ranvier.CE`{fsharp} (`open Ranvier`{fsharp} +
`open Ranvier.CE`{fsharp}):

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

[^glitch-free]: [`glitch_free_read`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.WholeGraph.html#glitch_free_read), [`convergence`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.WholeGraph.html#convergence).
[^cutoff]: [`cutoff`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Runs.html#cutoff), [`resolve_clean_unmoved`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Check.html#resolve_clean_unmoved).
[^latest-reads]: [`run_end_edges_are_latest_reads`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Runs.html#run_end_edges_are_latest_reads).
[^sources-end-run]: [`sources_end_run_spec`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Heap.SourceList.html#sources_end_run_spec).
[^memo-scope-violation]: [`memo_scope_violation_returns`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#memo_scope_violation_returns).
[^dispose-reverse]: [`dispose_reverse_order`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#dispose_reverse_order).
[^disposed-memo]: [`disposed_memo_answers`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#disposed_memo_answers), [`disposed_memo_no_refresh`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Check.html#disposed_memo_no_refresh).
