Collection views and aggregates
Collection views derive live Projection instances from an upstream projection or KeyedCollection.Rows, re-running user functions only for changed rows.
Aggregates fold a projection into a Memo<'S> owned by the calling scope. Both require row memos and raise NotSupportedException on createProjectionOnce.
Complexity
| Operator | Output | Sparse row edit / small delta cost | Dense burst / full reorder | Space |
|---|---|---|---|---|
Projection.map, mapWith | Projection<'K, 'U> | per demanded changed row; key delta | on reset | |
Projection.filter, choose, partition | Projection (or pair) | Fenwick rank + Keys splice per flip ( Some→Some in choose) | linear slot scan | |
Projection.distinctBy | Projection<'K, 'V> | non-leader edit; two-bucket + Fenwick splice on leader change | bucket rebuild | |
Projection.sortBy, sortByDescending | Projection<'K, 'V> | neighbour check if order holds; binary search + slice shift per move | sort | |
Projection.take, skip, sub | Projection<'K, 'V> | ; shifting by creates/disposes at most rows | ||
Projection.groupBy / Grouping.aggregate | Grouping<'G, 'K, 'V> / Projection<'G, 'S> | untouched groups; bucket move | scan | |
Projection.foldGroup, foldGroupBy, sumBy, countBy, exists, forall, tryAverageBy (averageBy) | Memo<'S> | inverse update (subtract old, add new); key delta | (NaN/Infinity float fallback or reset) | |
Projection.tryMinBy, tryMaxBy (minBy, maxBy) | Memo<'V option> (Memo<'V>) | when rank unchanged; tournament tree sift on rank edit, removal, or tail append | on non-tail insert or reorder | |
Projection.tryFind, tryFindKey, tryPick (find, findKey, pick) | Memo<_ option> (Memo<_>) | non-flipping edit; internal filter/choose Fenwick splice on flip | ||
Projection.fold | Memo<'S> | folder calls over cached values in Keys order (reads only changed rows) | ||
Projection.length, isEmpty, tryHead, tryLast, tryItem (head, last, item) | Memo<_> | (length/isEmpty ignore row edits; positional memos read only the indexed row) |
Per-row check cutoffs,1 Fenwick rank splicing,2 local sort reinsertion,3 distinct bucket updates,4 group moves,5 tournament winner maintenance,6 and direct row observers / companion disposal7 are mechanically verified.
Filtered, sorted, and paged views
| Family | Operators | Notes |
|---|---|---|
| Filtering & deduplication | filter, partition, choose, distinctBy | partition shares one predicate pass across both views; choose keeps Keys quiet on Some-to-Some edits; distinctBy retains the first key per bucket. |
| Sorting | sortBy, sortByDescending | Stable on ties, places NaN last on .NET and Fable, and orders None before Some (after in sortByDescending). |
| Mapping & paging | map, mapWith, take, skip, sub | mapWith pairs with row { ... } in a per-key scope; take / skip / sub 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); failed rows leave Keys and raise on Get / TryGet. |
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
([|3; 1; 4|], [|1; 2; 3|], ([|2|], [|1; 3; 4|]), [|3; 1|], 3, "Task #3: Docs (2h)")
Group rows
Projection.groupBy returns a Grouping<'G, 'K, 'V> (a Projection<'G, Projection<'K, 'V>>) 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 (GroupOf key queries a key's group).
Grouping.aggregate builds one aggregate Memo<'S> per active group inside that group's scope, disposing the memo if the group empties:
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
([(false, [|1; 3; 4|]); (true, [|2|])], ValueSome 5, 10)
Incremental aggregates
Change one row's estimate, then remove another row. sumBy updates in via inverse subtraction and addition, while countBy changes only when membership or predicate truth changes:
Example code
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)
]
| Aggregate family | Operators | Update semantics |
|---|---|---|
| Abelian inverse folds () | foldGroup, foldGroupBy, sumBy, countBy, exists, forall, tryAverageBy (averageBy) | Require subtract (add s v) v = s and reset to zero when empty (exists → false, forall → true). |
| Tournament extremes () | tryMinBy, tryMaxBy (minBy, maxBy) | Sticky-holder binary tournament tree; non-Option variants raise when empty. |
| First-match search | tryFind, tryFindKey, tryPick (find, findKey, pick) | First matching upstream row via internal Fenwick-backed filter/choose ( non-flipping edit, flip). |
| Positional & general ( / ) | length, isEmpty, tryHead, tryLast, tryItem, fold | length / isEmpty track Keys only; positional reads track one slot; fold re-folds cached values in when no inverse exists. |
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
(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, subtract, or folder are tracked and trigger an 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):
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
(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> (or its enclosing scope) detaches all row observers and disposes any internal helper views.