add_monoids: Add or Merge Measure Monoids

View source: R/20-api-generics.R

add_monoidsR Documentation

Add or Merge Measure Monoids

Description

Attaches one or more named measure_monoid() definitions to an existing immutable structure.

Usage

add_monoids(t, monoids, overwrite = FALSE)

Arguments

t

Immutable structure (flexseq and subclasses).

monoids

Named list of measure_monoid() objects.

overwrite

Logical; if TRUE, replace existing monoids with the same names. If FALSE, existing names are kept.

Details

Mechanics:

  • Each monoid name defines an independent accumulated measure over elements in the tree.

  • New monoids are computed for all elements and cached in the returned object.

  • Existing monoids are unchanged unless overwrite = TRUE.

  • Structural/reserved monoid names cannot be replaced.

Measure-function signatures:

  • flexseq: measure(entry) where entry is the stored element.

  • ordered_sequence: measure(entry) where entry is list(value, key).

  • priority_queue: measure(entry) where entry is list(value, priority).

  • interval_index: measure(entry) where entry is list(value, start, end).

This operation is persistent: t is not modified.

Use this when you want fast predicate scans (for example with locate_by_predicate(), split_by_predicate(), split_around_by_predicate()) driven by domain-specific accumulated values.

Value

A persistent copy with updated monoid definitions and cached measures.

See Also

measure_monoid(), get_measure(), get_measures()

Examples

x <- flexseq(10, 20, 30)

running_sum <- measure_monoid(`+`, 0, as.numeric)
x2 <- add_monoids(x, list(sum = running_sum))
attr(x2, "measures")$sum

# Use the monoid in a split query
split_around_by_predicate(x2, function(v) v >= 30, "sum")

# Overwrite an existing monoid definition
running_count <- measure_monoid(`+`, 0L, function(e) 1L)
x3 <- add_monoids(x2, list(sum = running_count), overwrite = TRUE)
attr(x3, "measures")$sum

Immutables documentation built on April 29, 2026, 1:06 a.m.