Skip to content

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

OperatorOutputSparse row edit / small delta costDense burst / full reorderSpace
Projection.map, mapWithProjection<'K, 'U>O(1)O(1) per demanded changed row; O(Δ)O(\Delta) key deltaO(N)O(N) on resetO(N)O(N)
Projection.filter, choose, partitionProjection (or pair)O(log⁡N)O(\log N) Fenwick rank + Keys splice per flip (O(1)O(1) Some→Some in choose)O(N)O(N) linear slot scanO(N)O(N)
Projection.distinctByProjection<'K, 'V>O(1)O(1) non-leader edit; O(log⁡N)O(\log N) two-bucket + Fenwick splice on leader changeO(N)O(N) bucket rebuildO(N)O(N)
Projection.sortBy, sortByDescendingProjection<'K, 'V>O(1)O(1) neighbour check if order holds; O(log⁡N)O(\log N) binary search + slice shift per moveO(Nlog⁡N)O(N \log N) sortO(N)O(N)
Projection.take, skip, subProjection<'K, 'V>O(window)O(\text{window}); shifting by dd creates/disposes at most dd rowsO(window)O(\text{window})O(window)O(\text{window})
Projection.groupBy / Grouping.aggregateGrouping<'G, 'K, 'V> / Projection<'G, 'S>O(1)O(1) untouched groups; O(∣src∣+∣dst∣+Glog⁡G)O(\lvert\text{src}\rvert + \lvert\text{dst}\rvert + G \log G) bucket moveO(N+G)O(N + G) scanO(N+G)O(N + G)
Projection.foldGroup, foldGroupBy, sumBy, countBy, exists, forall, tryAverageBy (averageBy)Memo<'S>O(1)O(1) inverse update (subtract old, add new); O(Δ)O(\Delta) key deltaO(N)O(N) (NaN/Infinity float fallback or reset)O(N)O(N)
Projection.tryMinBy, tryMaxBy (minBy, maxBy)Memo<'V option> (Memo<'V>)O(1)O(1) when rank unchanged; O(log⁡N)O(\log N) tournament tree sift on rank edit, removal, or tail appendO(N)O(N) on non-tail insert or reorderO(N)O(N)
Projection.tryFind, tryFindKey, tryPick (find, findKey, pick)Memo<_ option> (Memo<_>)O(1)O(1) non-flipping edit; O(log⁡N)O(\log N) internal filter/choose Fenwick splice on flipO(N)O(N)O(N)O(N)
Projection.foldMemo<'S>O(N)O(N) folder calls over cached values in Keys order (reads only changed rows)O(N)O(N)O(N)O(N)
Projection.length, isEmpty, tryHead, tryLast, tryItem (head, last, item)Memo<_>O(1)O(1) (length/isEmpty ignore row edits; positional memos read only the indexed row)O(1)O(1)O(1)O(1)

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

FamilyOperatorsNotes
Filtering & deduplicationfilter, partition, choose, distinctBypartition shares one predicate pass across both views; choose keeps Keys quiet on Some-to-Some edits; distinctBy retains the first key per bucket.
SortingsortBy, sortByDescendingStable on ties, places NaN last on .NET and Fable, and orders None before Some (after in sortByDescending).
Mapping & pagingmap, mapWith, take, skip, submapWith pairs with row { ... } in a per-key scope; take / skip / sub accept dynamic signal-driven offset and count thunks.
Pending & failed rowsAll viewsPending 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 O(1)O(1) 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)
    ]
Hover a node for its state; click it for why it last ran.

Aggregate familyOperatorsUpdate semantics
Abelian inverse folds (O(1)O(1))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 (O(log⁡N)O(\log N))tryMinBy, tryMaxBy (minBy, maxBy)Sticky-holder binary tournament tree; non-Option variants raise when empty.
First-match searchtryFind, tryFindKey, tryPick (find, findKey, pick)First matching upstream row via internal Fenwick-backed filter/choose (O(1)O(1) non-flipping edit, O(log⁡N)O(\log N) flip).
Positional & general (O(1)O(1) / O(N)O(N))length, isEmpty, tryHead, tryLast, tryItem, foldlength / isEmpty track Keys only; positional reads track one slot; fold re-folds cached values in O(N)O(N) 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 O(N)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):

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.

Edit this page