Construct a Measure Monoid Specification
Source:R/30-api-flexseq-measure-monoid.R
measure_monoid.RdDefines how element-level values are measured and combined as accumulated tree metadata.
Details
A measure monoid has three parts:
measure(entry): maps each stored leaf entry to a measure value.f(left, right): combines two measure values.i: identity value forf.
Requirements:
fshould be associative.ishould satisfyf(i, x) == xandf(x, i) == x.measure()outputs must be compatible withfandi.
Developer APIs are leaf-entry oriented:
flexseq: entry is the stored user element.ordered_sequence: entry islist(value, key).priority_queue: entry islist(value, priority).interval_index: entry islist(value, start, end).
measure_monoid() only constructs the specification; it becomes active after
being attached to a structure via add_monoids().
Examples
sum_m <- measure_monoid(`+`, 0, as.numeric)
x <- as_flexseq(1:5)
x2 <- add_monoids(x, list(sum = sum_m))
attr(x2, "measures")$sum
#> [1] 15
split_around_by_predicate(x2, function(v) v >= 6, "sum")
#> $left
#> Unnamed flexseq with 2 elements.
#>
#> Elements:
#>
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
#>
#>
#> $value
#> [1] 3
#>
#> $right
#> Unnamed flexseq with 2 elements.
#>
#> Elements:
#>
#> [[1]]
#> [1] 4
#>
#> [[2]]
#> [1] 5
#>
#>
# Count elements
count_m <- measure_monoid(`+`, 0L, function(el) 1L)
x3 <- add_monoids(x, list(count = count_m))
attr(x3, "measures")$count
#> [1] 5
# Character-width accumulation
width_m <- measure_monoid(`+`, 0L, function(el) nchar(as.character(el)))
s <- as_flexseq(c("aa", "b", "cccc"))
s2 <- add_monoids(s, list(width = width_m))
attr(s2, "measures")$width
#> [1] 7