# Lookups and selectors

Unlike a [projection](collections.fsx), a `Lookup<'K, 'V>`{fsharp} maintains no `Keys`{fsharp}
array: it creates per-key cells on demand over an open key domain, keeps them only while observed,
and pushes targeted invalidations when a shared upstream state changes.

## Selectors

`createSelector source`{fsharp} returns a `Lookup<'K, bool>`{fsharp} where `Get key`{fsharp} is
`true`{fsharp} for the currently selected key and `false`{fsharp} for every other key (keys
compare structurally).

A dedicated `SelectorLookup`{fsharp} tracks the previous selection and invalidates at most
`{prev, next}` in $O(1)$ time with zero intermediate list or buffer allocations:

```fsharp
let selected = signal { return 1 }
let isSelected = createSelector (fun () -> selected.Value)
selected.Value <- 3
[ for k in 1..4 -> k, isSelected.Get k ]
```

```text
[(1, false); (2, false); (3, true); (4, false)]
```

Moving the selection wakes only the deselected and newly selected keys while every untouched key
does `0` recomputations:

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

```fsharp
let mapSelected = signal { return 1 }
let mapIsSelected = createSelector (fun () -> mapSelected.Value)
let mutable runs1 = 0
let mutable runs2 = 0
let mutable runs3 = 0

let sel1 =
    createMemo (fun _ ->
        runs1 <- runs1 + 1
        mapIsSelected.Get 1)

let sel2 =
    createMemo (fun _ ->
        runs2 <- runs2 + 1
        mapIsSelected.Get 2)

let sel3 =
    createMemo (fun _ ->
        runs3 <- runs3 + 1
        mapIsSelected.Get 3)

effect { let! v = sel1 in printfn "key 1 = %b" v }
effect { let! v = sel2 in printfn "key 2 = %b" v }
effect { let! v = sel3 in printfn "key 3 = %b" v }

controls
    [
        button "Select 2" (fun () -> mapSelected.Value <- 2)
        |> describe "Only keys 1 and 2 recompute; key 3 does 0 recomputations."
        |> expect "Keys 1 and 2 flip while key 3 stays at 1 run." (fun () ->
            not sel1.Peek
            && sel2.Peek
            && not sel3.Peek
            && runs1 = 2
            && runs2 = 2
            && runs3 = 1)
        button "Select 3" (fun () -> mapSelected.Value <- 3)
        |> describe "Only keys 2 and 3 recompute; key 1 does 0 recomputations."
        |> expect "Keys 2 and 3 flip while key 1 stays at 2 runs." (fun () ->
            not sel1.Peek
            && not sel2.Peek
            && sel3.Peek
            && runs1 = 2
            && runs2 = 3
            && runs3 = 2)
    ]
```

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

</div>


## Lookups

`createLookup f affected source`{fsharp} holds `source ()`{fsharp} in an internal state memo and
computes `f state key`{fsharp} for each observed key.

On each unequal state transition `prev -> next`{fsharp}, it recomputes only the live cells named
by `affected prev next`{fsharp} in $O(\text{affected})$ time, ahead of woken
effects.[^lookup-pass]

:::warning The `affected` function is a soundness contract
`affected prev next`{fsharp} must yield every key whose result `f state key`{fsharp} can differ
between `prev`{fsharp} and `next`{fsharp}.

Omitting a changed key leaves its live cell stale; naming an unchanged key costs one extra
recomputation that cuts off under the graph's equality policy. Both `f`{fsharp} and
`affected`{fsharp} are pure (`source`{fsharp} is owning).
:::

Pointwise reads follow the unified naming across Ranvier's keyed primitives:

| Operation | CE descriptor | Behaviour |
| --- | --- | --- |
| `lookup.Get key`{fsharp} / `Lookup.get key lookup`{fsharp} (`'V`{fsharp}) | `Lookup.at key lookup`{fsharp} | Demand-creating tracked read; raises `NotReadyException`{fsharp} while pending or the cell/source failure. |
| `lookup.TryGet key`{fsharp} / `Lookup.tryGet key lookup`{fsharp} (`'V voption`{fsharp}) | `Lookup.tryAt key lookup`{fsharp} | Tracked read of an already-live cell (`ValueSome v`{fsharp}), or `ValueNone`{fsharp} untracked (`0` cells allocated when cold). |
| `lookup.TryRead key`{fsharp} / `Lookup.tryRead key lookup`{fsharp} (`Reading<'V>`{fsharp}) | `tryRead (Lookup.at key lookup)`{fsharp} | Non-throwing demand-creating tracked read returning `Ready v`{fsharp}, `Pending`{fsharp}, or `Failed ex`{fsharp}. |
| `lookup.CellCount`{fsharp} | — | Untracked count of resident cells; orphaned cells (`0` observers) evict automatically on the next transition or read. |

```fsharp
let stock = signal { return Map [ "apples", 3; "pears", 0 ] }

let changedKeys (prev: Map<string, int>) (next: Map<string, int>) =
    seq {
        for KeyValue (k, v) in prev do
            if next.TryFind k <> Some v then
                yield k

        for KeyValue (k, _) in next do
            if not (prev.ContainsKey k) then
                yield k
    }

let onHand =
    createLookup (fun (m: Map<string, int>) k -> m.TryFind k |> Option.defaultValue 0) changedKeys (fun () -> stock.Value)

let coldPear = memo { let! count = Lookup.tryAt "pears" onHand in return count }
let appleCount = memo { let! count = Lookup.at "apples" onHand in return count }
let warmApple = memo { let! count = Lookup.tryAt "apples" onHand in return count }
let plumReading = Lookup.tryRead "plums" onHand
stock |> Signal.update (Map.add "apples" 4) // refreshes "apples" and evicts unobserved "plums"

coldPear.Value, appleCount.Value, warmApple.Value, plumReading, onHand.CellCount
```

```text
(ValueNone, 4, ValueSome 4, Ready 0, 1)
```

## Lookup vs MemoTable

Choose between `createSelector`{fsharp}, `createLookup`{fsharp}, and
[`MemoTable<'K, 'V>`](memo-tables.md) based on how keys depend on upstream state and how memory is
bounded:

| Primitive | Upstream dependency model | Invalidation & evaluation | Memory retention |
| --- | --- | --- | --- |
| `createSelector`{fsharp} (`Lookup<'K, bool>`{fsharp}) | One selected key `'K`{fsharp} | Push: $O(1)$ direct `2`-key invalidation (`prev`{fsharp} & `next`{fsharp}) | `0` unobserved cells; $O(\text{observed keys})$ |
| `createLookup`{fsharp} (`Lookup<'K, 'V>`{fsharp}) | One shared state `'S`{fsharp} + `affected prev next`{fsharp} diff | Push: $O(\text{affected})$ targeted cell recomputation; `f`{fsharp} reads `'S`{fsharp} untracked | `0` unobserved cells; auto-evicts orphaned keys on next read/transition |
| `memoTable`{fsharp} (`MemoTable<'K, 'V>`{fsharp}) | Arbitrary independent `IReactive`{fsharp} reads per key (`let! k = memoTable.key`{fsharp}) + recursive `table.Get`{fsharp} | Pull-lazy per-slot `Memo`{fsharp} nodes; $O(1)$ amortized hit; optional `onCycle`{fsharp} recovery | Bounded weighted-LRU payloads (`maxEntries`{fsharp} / `maxWeight`{fsharp}), eviction-invariant `stamp`{fsharp} cutoff, and `maxDormant`{fsharp} slot cap |

- Reach for **`createSelector`{fsharp}** whenever rows test equality against a single active ID
  (selection, focus, active tab, hovered item).

- Reach for **`createLookup`{fsharp}** when one upstream map or state snapshot changes and
  `affected prev next`{fsharp} can name the touched keys without maintaining independent
  dependency lists per key.

- Reach for **`MemoTable`{fsharp}** ([Memo tables](memo-tables.md)) when different keys read
  different signals or memos, when keys call each other recursively, or when unobserved heavy
  values should remain cached up to an explicit count or byte-weight budget.

[^lookup-pass]: [`pass_runs_before_effect`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#pass_runs_before_effect), [`run_passes_returns_clean`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#run_passes_returns_clean), [`core_queue_drain_refines_priority`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#core_queue_drain_refines_priority).
