% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/20-api-generics.R
\name{add_monoids}
\alias{add_monoids}
\title{Add or Merge Measure Monoids}
\usage{
add_monoids(t, monoids, overwrite = FALSE)
}
\arguments{
\item{t}{Immutable structure (\code{flexseq} and subclasses).}

\item{monoids}{Named list of \code{\link[=measure_monoid]{measure_monoid()}} objects.}

\item{overwrite}{Logical; if \code{TRUE}, replace existing monoids with the same
names. If \code{FALSE}, existing names are kept.}
}
\value{
A persistent copy with updated monoid definitions and cached measures.
}
\description{
Attaches one or more named \code{\link[=measure_monoid]{measure_monoid()}} definitions to an existing
immutable structure.
}
\details{
Mechanics:
\itemize{
\item Each monoid name defines an independent accumulated measure over elements in the tree.
\item New monoids are computed for all elements and cached in the returned object.
\item Existing monoids are unchanged unless \code{overwrite = TRUE}.
\item Structural/reserved monoid names cannot be replaced.
}

Measure-function signatures:
\itemize{
\item \code{flexseq}: \code{measure(entry)} where \code{entry} is the stored element.
\item \code{ordered_sequence}: \code{measure(entry)} where \code{entry} is \code{list(value, key)}.
\item \code{priority_queue}: \code{measure(entry)} where \code{entry} is \code{list(value, priority)}.
\item \code{interval_index}: \code{measure(entry)} where \code{entry} is \code{list(value, start, end)}.
}

This operation is persistent: \code{t} is not modified.

Use this when you want fast predicate scans (for example with
\code{\link[=locate_by_predicate]{locate_by_predicate()}}, \code{\link[=split_by_predicate]{split_by_predicate()}}, \code{\link[=split_around_by_predicate]{split_around_by_predicate()}})
driven by domain-specific accumulated values.
}
\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
}
\seealso{
\code{\link[=measure_monoid]{measure_monoid()}}, \code{\link[=get_measure]{get_measure()}}, \code{\link[=get_measures]{get_measures()}}
}
