# Collection views and aggregates

Collection views derive live `Projection`{fsharp} instances from an upstream
[projection or `KeyedCollection.Rows`](collections.fsx), re-running user functions only for
changed rows.

Aggregates fold a projection into a `Memo<'S>`{fsharp} owned by the calling scope. Both require
row memos and raise `NotSupportedException`{fsharp} on `createProjectionOnce`{fsharp}.

## Complexity

| Operator | Output | Sparse row edit / small delta cost | Dense burst / full reorder | Space |
| --- | --- | --- | --- | --- |
| `Projection.map`{fsharp}, `mapWith`{fsharp} | `Projection<'K, 'U>`{fsharp} | $O(1)$ per demanded changed row; $O(\Delta)$ key delta | $O(N)$ on reset | $O(N)$ |
| `Projection.filter`{fsharp}, `choose`{fsharp}, `partition`{fsharp} | `Projection`{fsharp} (or pair) | $O(\log N)$ Fenwick rank + `Keys`{fsharp} splice per flip ($O(1)$ `Some`{fsharp}→`Some`{fsharp} in `choose`{fsharp}) | $O(N)$ linear slot scan | $O(N)$ |
| `Projection.distinctBy`{fsharp} | `Projection<'K, 'V>`{fsharp} | $O(1)$ non-leader edit; $O(\log N)$ two-bucket + Fenwick splice on leader change | $O(N)$ bucket rebuild | $O(N)$ |
| `Projection.sortBy`{fsharp}, `sortByDescending`{fsharp} | `Projection<'K, 'V>`{fsharp} | $O(1)$ neighbour check if order holds; $O(\log N)$ binary search + slice shift per move | $O(N \log N)$ sort | $O(N)$ |
| `Projection.take`{fsharp}, `skip`{fsharp}, `sub`{fsharp} | `Projection<'K, 'V>`{fsharp} | $O(\text{window})$; shifting by $d$ creates/disposes at most $d$ rows | $O(\text{window})$ | $O(\text{window})$ |
| `Projection.groupBy`{fsharp} / `Grouping.aggregate`{fsharp} | `Grouping<'G, 'K, 'V>`{fsharp} / `Projection<'G, 'S>`{fsharp} | $O(1)$ untouched groups; $O(\lvert\text{src}\rvert + \lvert\text{dst}\rvert + G \log G)$ bucket move | $O(N + G)$ scan | $O(N + G)$ |
| `Projection.foldGroup`{fsharp}, `foldGroupBy`{fsharp}, `sumBy`{fsharp}, `countBy`{fsharp}, `exists`{fsharp}, `forall`{fsharp}, `tryAverageBy`{fsharp} (`averageBy`{fsharp}) | `Memo<'S>`{fsharp} | $O(1)$ inverse update (`subtract`{fsharp} old, `add`{fsharp} new); $O(\Delta)$ key delta | $O(N)$ (`NaN`{fsharp}/`Infinity`{fsharp} float fallback or reset) | $O(N)$ |
| `Projection.tryMinBy`{fsharp}, `tryMaxBy`{fsharp} (`minBy`{fsharp}, `maxBy`{fsharp}) | `Memo<'V option>`{fsharp} (`Memo<'V>`{fsharp}) | $O(1)$ when rank unchanged; $O(\log N)$ tournament tree sift on rank edit, removal, or tail append | $O(N)$ on non-tail insert or reorder | $O(N)$ |
| `Projection.tryFind`{fsharp}, `tryFindKey`{fsharp}, `tryPick`{fsharp} (`find`{fsharp}, `findKey`{fsharp}, `pick`{fsharp}) | `Memo<_ option>`{fsharp} (`Memo<_>`{fsharp}) | $O(1)$ non-flipping edit; $O(\log N)$ internal `filter`{fsharp}/`choose`{fsharp} Fenwick splice on flip | $O(N)$ | $O(N)$ |
| `Projection.fold`{fsharp} | `Memo<'S>`{fsharp} | $O(N)$ `folder`{fsharp} calls over cached values in `Keys`{fsharp} order (reads only changed rows) | $O(N)$ | $O(N)$ |
| `Projection.length`{fsharp}, `isEmpty`{fsharp}, `tryHead`{fsharp}, `tryLast`{fsharp}, `tryItem`{fsharp} (`head`{fsharp}, `last`{fsharp}, `item`{fsharp}) | `Memo<_>`{fsharp} | $O(1)$ (`length`{fsharp}/`isEmpty`{fsharp} ignore row edits; positional memos read only the indexed row) | $O(1)$ | $O(1)$ |

Per-row check cutoffs,[^row-cutoff] Fenwick rank splicing,[^fenwick-rank] local sort
reinsertion,[^sortview-reinsert] distinct bucket updates,[^distinct-bucket] group
moves,[^grouping-move] tournament winner maintenance,[^tournament-winner] and direct row observers
/ companion disposal[^direct-observer] are mechanically verified.

## Filtered, sorted, and paged views

| Family | Operators | Notes |
| --- | --- | --- |
| **Filtering & deduplication** | `filter`{fsharp}, `partition`{fsharp}, `choose`{fsharp}, `distinctBy`{fsharp} | `partition`{fsharp} shares one predicate pass across both views; `choose`{fsharp} keeps `Keys`{fsharp} quiet on `Some`{fsharp}-to-`Some`{fsharp} edits; `distinctBy`{fsharp} retains the first key per bucket. |
| **Sorting** | `sortBy`{fsharp}, `sortByDescending`{fsharp} | Stable on ties, places `NaN`{fsharp} last on `.NET` and Fable, and orders `None`{fsharp} before `Some`{fsharp} (`after` in `sortByDescending`{fsharp}). |
| **Mapping & paging** | `map`{fsharp}, `mapWith`{fsharp}, `take`{fsharp}, `skip`{fsharp}, `sub`{fsharp} | `mapWith`{fsharp} pairs with `row { ... }`{fsharp} in a per-key scope; `take`{fsharp} / `skip`{fsharp} / `sub`{fsharp} accept dynamic signal-driven offset and count thunks. |
| **Pending & failed rows** | All views | Pending predicates/sort keys retain last settled membership or order (unsettled keys appear in `PendingKeys`{fsharp}); failed rows leave `Keys`{fsharp} and raise on `Get`{fsharp} / `TryGet`{fsharp}. |

```fsharp
type TaskItem =
    {
        Id: int
        Title: string
        Estimate: int
        Done: bool
    }

let tasks =
    signal {
        return
            [
                {
                    Id = 1
                    Title = "Spec"
                    Estimate = 3
                    Done = false
                }
                {
                    Id = 2
                    Title = "Build"
                    Estimate = 5
                    Done = true
                }
                {
                    Id = 3
                    Title = "Docs"
                    Estimate = 2
                    Done = false
                }
                {
                    Id = 4
                    Title = "Release"
                    Estimate = 5
                    Done = false
                }
            ]
    }

let rows = createProjection (fun (t: TaskItem) -> t.Id) id (fun () -> tasks.Value)
let openRows = rows |> Projection.filter (fun t -> not t.Done)

let openEstimates =
    rows
    |> Projection.choose (fun t -> if t.Done then None else Some t.Estimate)

let byEstimate = openRows |> Projection.sortBy _.Estimate
let onePerEstimate = rows |> Projection.distinctBy _.Estimate
let doneSide, openSide = rows |> Projection.partition _.Done

let prefix = signal { return "Task" }

let rowBadges =
    openRows
    |> Projection.mapWith (fun id readTask ->
        row {
            let! t = readTask
            and! label = prefix
            return $"{label} #{id}: {t.Title} ({t.Estimate}h)"
        })

let page = signal { return 0 }

let visiblePage =
    byEstimate
    |> Projection.sub (fun () -> page.Value * 2) (fun () -> 2)

byEstimate.Keys, onePerEstimate.Keys, (doneSide.Keys, openSide.Keys), visiblePage.Keys, openEstimates.Get 1, rowBadges.Get 3
```

```text
([|3; 1; 4|], [|1; 2; 3|], ([|2|], [|1; 3; 4|]), [|3; 1|], 3, "Task #3: Docs (2h)")
```

## Group rows

`Projection.groupBy`{fsharp} returns a `Grouping<'G, 'K, 'V>`{fsharp} (a
`Projection<'G, Projection<'K, 'V>>`{fsharp}) ordered by each group's first upstream member.

When a row changes group, it leaves its old inner view and joins its new one in a single pass
while untouched groups stay asleep; emptied inner views are disposed, and never-settled or failed
group keys appear in `UngroupedKeys`{fsharp} (`GroupOf key`{fsharp} queries a key's group).

`Grouping.aggregate`{fsharp} builds one aggregate `Memo<'S>`{fsharp} per active group inside that
group's scope, disposing the memo if the group empties:

```fsharp
let byDone = rows |> Projection.groupBy _.Done

let hoursByDone =
    byDone
    |> Grouping.aggregate (Projection.sumBy _.Estimate)

let openGroupHours =
    memo {
        let! hrs = Projection.tryAt false hoursByDone
        return ValueOption.defaultValue 0 hrs
    }

[ for flag in byDone.Keys -> flag, (byDone.Get flag).Keys ], hoursByDone.TryGet true, openGroupHours.Value
```

```text
([(false, [|1; 3; 4|]); (true, [|2|])], ValueSome 5, 10)
```

## Incremental aggregates

Change one row's estimate, then remove another row. `sumBy`{fsharp} updates in $O(1)$ via inverse
subtraction and addition, while `countBy`{fsharp} changes only when membership or predicate truth
changes:

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

```fsharp
let estimates = createSignal [ 1, 3; 2, 5; 3, 2 ]
let estimateRows = createProjection fst snd (fun () -> estimates.Value)
let estimateTotal = estimateRows |> Projection.sumBy id
let estimateCount = estimateRows |> Projection.countBy (fun _ -> true)
createEffect (fun () -> printfn "estimate = %d, tasks = %d" estimateTotal.Value estimateCount.Value)

controls
    [
        button "Estimate task 1 at 8" (fun () ->
            estimates.Value <-
                estimates.Value
                |> List.map (fun (key, estimate) -> key, (if key = 1 then 8 else estimate)))
        |> describe "One contribution grows by 5; membership stays at three tasks."
        |> expect "One contribution grows by 5; membership stays at three tasks." (fun () -> estimateTotal.Peek = 15 && estimateCount.Peek = 3)
        button "Remove task 2" (fun () ->
            estimates.Value <-
                estimates.Value
                |> List.filter (fun (key, _) -> key <> 2))
        |> describe "Removing the estimate of 5 leaves a total of 10 across two tasks."
        |> expect "Removing the estimate of 5 leaves a total of 10 across two tasks." (fun () -> estimateTotal.Peek = 10 && estimateCount.Peek = 2)
    ]
```

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

</div>


| Aggregate family | Operators | Update semantics |
| --- | --- | --- |
| **Abelian inverse folds ($O(1)$)** | `foldGroup`{fsharp}, `foldGroupBy`{fsharp}, `sumBy`{fsharp}, `countBy`{fsharp}, `exists`{fsharp}, `forall`{fsharp}, `tryAverageBy`{fsharp} (`averageBy`{fsharp}) | Require `subtract (add s v) v = s`{fsharp} and reset to `zero`{fsharp} when empty (`exists`{fsharp} → `false`{fsharp}, `forall`{fsharp} → `true`{fsharp}). |
| **Tournament extremes ($O(\log N)$)** | `tryMinBy`{fsharp}, `tryMaxBy`{fsharp} (`minBy`{fsharp}, `maxBy`{fsharp}) | Sticky-holder binary tournament tree; non-Option variants raise when empty. |
| **First-match search** | `tryFind`{fsharp}, `tryFindKey`{fsharp}, `tryPick`{fsharp} (`find`{fsharp}, `findKey`{fsharp}, `pick`{fsharp}) | First matching upstream row via internal Fenwick-backed filter/choose ($O(1)$ non-flipping edit, $O(\log N)$ flip). |
| **Positional & general ($O(1)$ / $O(N)$)** | `length`{fsharp}, `isEmpty`{fsharp}, `tryHead`{fsharp}, `tryLast`{fsharp}, `tryItem`{fsharp}, `fold`{fsharp} | `length`{fsharp} / `isEmpty`{fsharp} track `Keys`{fsharp} only; positional reads track one slot; `fold`{fsharp} re-folds cached values in $O(N)$ when no inverse exists. |

```fsharp
let remainingHours =
    rows
    |> Projection.sumBy (fun t -> if t.Done then 0 else t.Estimate)

let doneCount = rows |> Projection.countBy _.Done
let anyDone = rows |> Projection.exists _.Done
let allDone = rows |> Projection.forall _.Done

let meanHours =
    rows
    |> Projection.tryAverageBy (fun t -> float t.Estimate)

let shortestId =
    rows
    |> Projection.tryMinBy _.Estimate
    |> Memo.map (Option.map _.Id)

let longestId =
    rows
    |> Projection.tryMaxBy _.Estimate
    |> Memo.map (Option.map _.Id)

let orderedIds =
    byEstimate
    |> Projection.fold (fun acc t -> acc @ [ t.Id ]) []

let totalCount = rows |> Projection.length

let topOpen =
    byEstimate
    |> Projection.tryHead
    |> Memo.map (Option.map fst)

let firstFiveHourKey =
    rows
    |> Projection.tryFindKey (fun t -> t.Estimate >= 5)

remainingHours.Value,
doneCount.Value,
(anyDone.Value, allDone.Value),
meanHours.Value,
(shortestId.Value, longestId.Value),
orderedIds.Value,
totalCount.Value,
topOpen.Value,
firstFiveHourKey.Value
```

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

External signals or memos read inside `add`{fsharp}, `subtract`{fsharp}, or `folder`{fsharp} are
tracked and trigger an $O(N)$ re-fold of cached row values when they change; never create owned
nodes inside aggregate callbacks (create them in the enclosing scope and read them inside):

```fsharp
let hourlyRate = signal { return 100 }

let totalBudget =
    rows
    |> Projection.foldGroup (fun sum t -> sum + t.Estimate * hourlyRate.Value) (fun sum t -> sum - t.Estimate * hourlyRate.Value) 0

let initialBudget = totalBudget.Value
hourlyRate.Value <- 150
initialBudget, totalBudget.Value
```

```text
(1500, 2250)
```

Pending rows retain their last settled contribution until their next settle, while failed rows
raise on aggregate reads and recover once settled. Disposing the aggregate `Memo<'S>`{fsharp} (or
its enclosing scope) detaches all row observers and disposes any internal helper views.

[^row-cutoff]: [`row_slot_check_cutoff_skips_pass`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#row_slot_check_cutoff_skips_pass).
[^fenwick-rank]: [`filter_incremental_step_refines_scan`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#filter_incremental_step_refines_scan), [`fenwick_sum_spec`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Heap.Collections.html#fenwick_sum_spec).
[^sortview-reinsert]: [`sortview_insert_remove_refines_sort`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#sortview_insert_remove_refines_sort).
[^distinct-bucket]: [`distinct_bucket_update_refines_scan`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#distinct_bucket_update_refines_scan).
[^grouping-move]: [`grouping_move_refines_scan`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#grouping_move_refines_scan).
[^tournament-winner]: [`tournament_winner_optimal_and_first`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#tournament_winner_optimal_and_first), [`tournament_point_update_refines_eval`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#tournament_point_update_refines_eval), [`sticky_holder_refines_extreme_scan`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#sticky_holder_refines_extreme_scan).
[^direct-observer]: [`direct_link_is_sources_add`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#direct_link_is_sources_add), [`adopt_companion_disposed_once`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#adopt_companion_disposed_once).
