ihb2032/MoonFrame/expr does not have a README file

    AggOp

    pub enum AggOp {
    Sum
    Mean
    Min
    Max
    Count
    Std
    Var
    Median
    NUnique
    First
    Last
    } derive(Eq,
    Debug
    )

    Aggregation tag carried by Expr::Agg — same read-only-not-priv rationale as BinOp. Evaluation inherits the shared reduction kernel's semantics wholesale: Sum / Mean propagate NaN and Std / Var (the sample statistics, ddof = 1) carry it through the mean; Min / Max and the order statistic Median skip it; Count counts non-null cells and NUnique the distinct non-null values (NaN one bucket); First / Last are positional and skip nothing.

    This variant list is mirrored by @series.ReduceOp, the constructible vocabulary the reduction kernel speaks (@expr.AggOp is read-only outside expr, so frame's reduce_op_of_agg maps each variant here onto its ReduceOp twin one-to-one). Keep the two lists in lockstep — a variant added here must be added to ReduceOp and to that 1:1 map, which alone is exhaustive, so the compiler flags a missed map arm but not a missed enum.

    BinOp

    pub enum BinOp {
    Add
    Sub
    Mul
    Div
    Eq
    Ne
    Lt
    Le
    Gt
    Ge
    And
    Or
    } derive(Eq,
    Debug
    )

    Binary operator tag carried by Expr::Binary. pub read-only rather than priv: a pub enum cannot carry a priv payload ([4046]), and the evaluator in frame must match the tag cross-package. Inert from the outside — no public API returns a bare BinOp, so users never name one; it is not re-exported through the facade.

    And / Or are the Kleene three-valued logical connectives (& / | at the call site), not bitwise operations; the comparison tags produce Bool columns under the evaluator's null-propagation rules.

    Expr

    A composable, introspectable column expression tree — the reified upgrade over the closure-based surfaces (the v0.1 row-predicate closure) and pre-materialised Series columns. An Expr is data: the evaluator in frame pattern-matches it, and the v0.4 lazy layer will print and rewrite it — none of which a closure can offer.

    The enum is pub (read-only): other packages — including frame, whose evaluator matches the tree cross-package — can inspect it but cannot construct variants ([4036]). The only way to build an Expr is the constructor functions (col / lit / lit_* / when), the operator impls and the methods in expr_ops.mbt, so every tree is well-formed by construction. Building an expression is total — unknown columns and dtype mismatches surface at evaluation time (in frame), never here.

    Variant tour (construction route in parentheses):
    • Col / Lit / LitSeries — leaves (col, lit / lit_*, lit_series). LitSeries embeds a whole pre-materialised @series.Series as a literal column: at evaluation it is used as-is, broadcasting when length 1 and otherwise matching the frame height (LengthMismatch on any other length). It is named after the series it carries, so its output column keeps the series' name unless an alias overrides it;
    • Binary — arithmetic + - * /, comparisons eq/ne/lt/le/gt/ge, Kleene logic &/| (also .land()/.lor() — and/or are reserved words);
    • Unary — -e, .not(), .is_null(), .is_not_null(), .is_nan(), .is_not_nan();
    • Agg — .sum()/.mean()/.min()/.max()/.count(), reducing its operand to a single value per evaluation scope;
    • Str — the string namespace (.str_to_uppercase() / .str_contains(p) / …), mapping each cell of its String operand through a StrOp transform;
    • Cast — .cast(dtype);
    • Alias — .with_alias(name) (alias is a reserved word), naming the result column;
    • Ternary — when(cond).then(a).otherwise(b);
    • FillNull / FillNan — .fill_null(value) / .fill_nan(value), carrying (operand, value). Semantically these are the guarded ternaries when(operand.is_not_null()).then(operand).otherwise(value) (resp. is_not_nan), but as dedicated nodes the operand appears — and is evaluated, rendered, and compared — once: the ternary lowering embedded self twice, so a chained coalesce (e.fill_null(a).fill_null(b)…) built an exponentially-sized tree;
    • Map — the closure escape hatch (.map_elements() / map_many()), applying an opaque host function row by row over its input columns. It carries a label (for Show / explain), the input expressions, and the function (Array[Scalar]) -> Scalar raise. The closure makes the variant un-derive-able, so Expr hand-writes Eq (below), @debug.Debug and Show (in explain.mbt), each treating the function as opaque — a Map is identified by its (label, inputs).
    impl Add for Expr
    impl BitAnd for Expr
    impl BitOr for Expr
    impl Div for Expr
    impl Eq for Expr
    impl Mul for Expr
    impl Neg for Expr
    impl Show for Expr
    impl Sub for Expr
    impl Debug for Expr

    Expr::cast

    Cast the operand to target at evaluation time, delegating to Series::cast (so the supported dtype pairs — and the Unsupported cases — are exactly the eager ones).

    Expr::children

    fn Expr::children(self : Expr) -> Array[Expr]

    The immediate sub-expressions of a node, left to right — the single place that encodes the tree's recursive shape. Every tree walk that recurses uniformly rides this: referenced_columns and output_name here, and the lazy optimizer's row_stable / group_cell_stable analyses across the package boundary (hence pub — methods live with their type). A new variant declares its child structure once, here, rather than in every walk. A Ternary lists all three arms with the condition first; the one walk that must skip the condition — output naming — special-cases it rather than reading children. A Map lists its input expressions (a fresh copy, so a caller can never alias — and mutate — the node's own inputs). Leaves (Col / Lit / LitSeries) have none — a LitSeries carries materialised data, not sub-expressions. Total — it only inspects shape.

    Expr::col

    fn Expr::col(name : String) -> Expr

    Reference a column by name. The name resolves at evaluation time — ColumnNotFound then if the frame has no such column; building the reference itself is total.

    Expr::count

    fn Expr::count(self : Expr) -> Expr

    Count of non-null cells of the operand over the evaluation scope (Series::count semantics).

    Expr::eq

    fn Expr::eq(self : Expr, other : Expr) -> Expr

    a.eq(b) — elementwise equality, producing a Bool column. The whole comparison family is methods, not operators: MoonBit pins the Eq / Compare traits to Bool / Int returns, so they cannot build an Expr — and the postfix method binds tighter than & / | anyway, so a.gt(x) & b.lt(y) needs none of the parentheses Polars' operator comparisons force. A null on either side nulls the output cell.

    Expr::explain

    fn Expr::explain(self : Expr) -> String

    The Show rendering as a String — the human-readable face of an expression for demos, docs, and (from L1 on) per-node plan lines in LazyFrame::explain.

    Expr::fill_nan

    fn Expr::fill_nan(self : Expr, value : Expr) -> Expr

    Replace every NaN cell of self with value, keeping the non-NaN cells (including true nulls) verbatim — Polars' fill_nan. The dual of fill_null: where fill_null replaces missing cells and leaves NaN (a value) alone, fill_nan replaces NaN and leaves nulls alone.

    It evaluates exactly like when(self.is_not_nan()).then(self).otherwise(value) — named after self (the operand), and a null cell — for which is_not_nan is null — falls through the Kleene ternary to a null result, never to value. The branches unify their dtype like any ternary (Int meets Float by promoting to Float, any other mismatch is a TypeMismatch). Unlike that ternary spelling, the dedicated FillNan node holds (and evaluates) self once, so a chain of fills stays linear in tree size and work. Building the node is total.

    Expr::fill_null

    fn Expr::fill_null(self : Expr, value : Expr) -> Expr

    Replace every null cell of self with value, keeping the non-null cells verbatim — Polars' fill_null (the value form), and a coalesce of self over value when value is itself a column. value is any expression: a literal (lit_int(0)), another column (col("fallback")), or a computed tree.

    It evaluates exactly like when(self.is_not_null()).then(self).otherwise(value) — the result is named after self (the filled column), never after value, so with_columns([col("x").fill_null(...)]) replaces "x" in place. The branches must unify their dtype the way a ternary's do — Int meets Float by promoting to Float, any other mismatch is a TypeMismatch at evaluation. A non-null NaN is a value (validity 1), so it is kept, not filled; only true nulls are replaced. Unlike that ternary spelling, the dedicated FillNull node holds (and evaluates) self once, so the chained-coalesce idiom (col("a").fill_null(col("b")).fill_null(lit_int(0))) stays linear in tree size and work — the lowering embedded self twice and grew exponentially with chain length. Building the node is total; errors surface when a consuming verb evaluates it.

    Expr::first

    fn Expr::first(self : Expr) -> Expr

    First cell of the operand over the evaluation scope, in row order, keeping the operand's dtype. Positional — a null first cell is null, an empty scope is null, and a present NaN passes through verbatim.

    Expr::ge

    fn Expr::ge(self : Expr, other : Expr) -> Expr

    a.ge(b) — elementwise >= (Bool column, null-propagating).

    Expr::gt

    fn Expr::gt(self : Expr, other : Expr) -> Expr

    a.gt(b) — elementwise > (Bool column, null-propagating).

    Expr::is_nan

    fn Expr::is_nan(self : Expr) -> Expr

    Bool column that is true where the operand holds the IEEE NaN value (Polars' is_nan). The operand must be numeric: an Int cell is never NaN (false), a Float cell is tested by Double::is_nan, and a non-numeric operand is a TypeMismatch at evaluation. Unlike is_null, this propagates nulls — a missing cell is neither NaN nor not, so the result cell is null — since NaN is a real value distinct from a missing one. Building the node is total.

    Expr::is_not_nan

    fn Expr::is_not_nan(self : Expr) -> Expr

    Bool column that is true where the operand is a non-NaN numeric value — the complement of is_nan on non-null cells, propagating nulls the same way (a missing cell stays null). Same numeric-operand requirement.

    Expr::is_not_null

    fn Expr::is_not_null(self : Expr) -> Expr

    Bool column that is true where the operand is non-null — the complement of is_null, equally total.

    Expr::is_null

    fn Expr::is_null(self : Expr) -> Expr

    Bool column that is true where the operand is null. Reads validity only, so the result is itself never null (total).

    Expr::last

    fn Expr::last(self : Expr) -> Expr

    Last cell of the operand over the evaluation scope, in row order, keeping the operand's dtype. The positional mirror of first.

    Expr::le

    fn Expr::le(self : Expr, other : Expr) -> Expr

    a.le(b) — elementwise <= (Bool column, null-propagating).

    Expr::lit

    Embed a literal Scalar. At evaluation it becomes a length-1 column broadcast against its siblings. Prefer the typed shorthands (lit_int / lit_float / lit_str / lit_bool), which avoid spelling the Scalar variant at call sites.

    Expr::lt

    fn Expr::lt(self : Expr, other : Expr) -> Expr

    a.lt(b) — elementwise < (Bool column, null-propagating).

    Expr::map_elements

    Apply a host closure to each row of self — the single-input escape hatch (Polars' map_elements). Where the operators and methods above cover the documented algebra, map_elements reaches past it: f receives the operand's cell as a @types.Scalar (a null cell as Scalar::Null) and returns the output cell. label names the step in explain / Show output — the function itself is opaque to introspection, equality, and the optimizer.

    Building the node is total; f runs at evaluation, once per row, and may raise (the error propagates from the consuming verb). The output column's dtype is that of the first non-null Scalar the closure returns — an all-null (or empty) result has no such cell, so its dtype falls back to self's own column backend, yielding an all-null (or empty) column of that dtype rather than the Unsupported a bare Null literal raises (Polars' tolerance of a null-returning map). The result is named after self (its leftmost column), so with_alias renames it. Use it inside with_columns / select / filter like any other expression; the optimizer treats it as a value barrier (it can raise on values), so no filter sinks across it.

    Expr::max

    fn Expr::max(self : Expr) -> Expr

    Maximum of the operand over the evaluation scope (Series::max semantics: NaN and nulls are skipped).

    Expr::mean

    fn Expr::mean(self : Expr) -> Expr

    Mean of the operand over the evaluation scope (Series::mean semantics: NaN propagates, nulls are skipped).

    Expr::median

    fn Expr::median(self : Expr) -> Expr

    Median of the operand over the evaluation scope. NaN and nulls are skipped (the order-statistic counterpart of min / max), an all-missing scope reduces to null, and a non-numeric operand is TypeMismatch. Always a Float (Int widens), so an even count averages its two middles.

    Expr::min

    fn Expr::min(self : Expr) -> Expr

    Minimum of the operand over the evaluation scope (Series::min semantics: NaN and nulls are skipped).

    Expr::n_unique

    fn Expr::n_unique(self : Expr) -> Expr

    Number of distinct non-null values of the operand over the evaluation scope (Series::n_unique semantics: every NaN is one bucket, -0.0 folds into +0.0). Total over every dtype, never null — an Int.

    Expr::ne

    fn Expr::ne(self : Expr, other : Expr) -> Expr

    a.ne(b) — elementwise inequality (Bool column, null-propagating).

    Expr::not

    fn Expr::not(self : Expr) -> Expr

    Kleene logical negation of a Bool expression (not(null) = null). A method because MoonBit has no overloadable unary ~ / !.

    Expr::output_name

    fn Expr::output_name(self : Expr) -> String

    The output-column name this expression produces — Polars' naming rule: an alias wins, otherwise the leftmost column reference's name, otherwise "literal" for a column-less tree. One rule, two consumers that must never drift apart: the eager materialisers in frame (with_columns / select / agg) name their output columns with it, and the lazy optimizer's projection pushdown uses it to know which names a deferred with_columns stage defines — a defined name need not exist in the stage's input, so pruning must not require it there. Total — naming walks plain data.

    Expr::referenced_columns

    fn Expr::referenced_columns(self : Expr) ->
    Set
    [String]

    Every column name the tree references, as a set — membership only; iteration order is neither significant nor guaranteed. A Ternary's condition counts — the optimizer must keep a column alive even if only the condition reads it — unlike output naming, which draws from the value branches only. Duplicates collapse: col("a") + col("a") references {"a"}.

    Expr::std

    fn Expr::std(self : Expr) -> Expr

    Sample standard deviation of the operand over the evaluation scope (ddof = 1, Polars' default): NaN propagates through the mean, nulls are skipped, fewer than two non-null cells reduce to null, and a non-numeric operand is TypeMismatch. Always a Float.

    Expr::str_contains

    fn Expr::str_contains(self : Expr, pattern : String) -> Expr

    A Bool column that is true where the cell contains pattern as a literal substring — Polars' str.contains(..., literal=True). Matching is always literal: there is no regex engine yet, so a regex contains is a future addition. Null cells stay null.

    Expr::str_ends_with

    fn Expr::str_ends_with(self : Expr, suffix : String) -> Expr

    A Bool column that is true where the cell ends with suffix (Polars str.ends_with). Null cells stay null.

    Expr::str_len_chars

    fn Expr::str_len_chars(self : Expr) -> Expr

    The number of Unicode characters in each cell of a String column, as an Int (Polars str.len_chars): a supplementary-plane character counts once, not as its two UTF-16 code units. Null cells stay null; an all-valid result rides the Numeric fast path like every computed numeric column.

    Expr::str_replace

    fn Expr::str_replace(self : Expr, pattern : String, value : String) -> Expr

    Replace the first literal occurrence of pattern with value in each cell of a String column — Polars' str.replace(..., literal=True). A cell without pattern is unchanged; null cells stay null.

    Expr::str_replace_all

    fn Expr::str_replace_all(self : Expr, pattern : String, value : String) -> Expr

    Replace every literal occurrence of pattern with value in each cell (Polars str.replace_all(..., literal=True)), the all-occurrences mirror of str_replace.

    Expr::str_starts_with

    fn Expr::str_starts_with(self : Expr, prefix : String) -> Expr

    A Bool column that is true where the cell starts with prefix (Polars str.starts_with). Null cells stay null.

    Expr::str_strip_chars

    fn Expr::str_strip_chars(self : Expr) -> Expr

    Strip leading and trailing ASCII whitespace — tab, newline, carriage-return, and space — from every cell of a String column, Polars' str.strip_chars with its default whitespace set. Null cells stay null.

    Expr::str_to_lowercase

    fn Expr::str_to_lowercase(self : Expr) -> Expr

    Lowercase the ASCII letters of a String column (the shape of Polars' str.to_lowercase, with str_to_uppercase's ASCII-only case-mapping caveat), the case mirror of str_to_uppercase.

    Expr::str_to_uppercase

    fn Expr::str_to_uppercase(self : Expr) -> Expr

    Uppercase the ASCII letters of a String column — the shape of Polars' str.to_uppercase, but case mapping is currently ASCII-only (like str_strip_chars' ASCII whitespace set): a non-ASCII letter (é, ß, Cyrillic, …) passes through unchanged rather than mapping. Null cells stay null, the result keeps the operand's column name, and a non-String operand is a TypeMismatch at evaluation. The leading method of the string namespace: every str_* method builds a Str node over a StrOp tag, evaluated cell by cell in frame.

    Expr::sum

    fn Expr::sum(self : Expr) -> Expr

    Sum of the operand over the evaluation scope (whole frame, or one group under agg). Inherits Series::sum semantics: NaN propagates, nulls are skipped, non-numeric operands are TypeMismatch.

    Expr::variance

    fn Expr::variance(self : Expr) -> Expr

    Sample variance of the operand over the evaluation scope (ddof = 1); the square of std, with the identical null / NaN / dtype rules. Always a Float. Spelled variance because var is a reserved MoonBit word (the with_alias / .land() situation), so Polars' var becomes variance.

    Expr::with_alias

    fn Expr::with_alias(self : Expr, name : String) -> Expr

    Name the result column ((col("revenue") - col("cost")).with_alias("profit")). Without an alias, an expression is named after its leftmost column reference, or "literal" for a column-less tree. Called with_alias — alias itself is a MoonBit reserved word.

    StrOp

    pub enum StrOp {
    ToUppercase
    ToLowercase
    StripChars
    LenChars
    Contains(String)
    StartsWith(String)
    EndsWith(String)
    Replace(String, String)
    ReplaceAll(String, String)
    } derive(Eq,
    Debug
    )

    String-operation tag carried by Expr::Str — same read-only-not-priv rationale as BinOp. Each variant is one method of the string namespace (Expr::str_*); the parameterised ones carry their literal arguments, so a tag is self-contained and structurally comparable — two Contains("a") tags are equal, Contains("a") and Contains("b") are not (which is why the Str arm of Expr's handwritten Eq can compare tags by ==). Every operation maps a String cell to its result cell by cell: ToUppercase / ToLowercase / StripChars / Replace / ReplaceAll yield a String, LenChars an Int (the Unicode character count), and the Contains / StartsWith / EndsWith predicates a Bool. Null cells pass through as null and a non-String operand is a TypeMismatch at evaluation; all are total (no value can raise), and matching is always literal — there is no regex engine yet.

    UnOp

    pub enum UnOp {
    Neg
    Not
    IsNull
    IsNotNull
    IsNan
    IsNotNan
    } derive(Eq,
    Debug
    )

    Unary operator tag carried by Expr::Unary — same read-only-not-priv rationale as BinOp. Neg is numeric negation (-e), Not is Kleene logical negation (not(null) = null), the null probes IsNull / IsNotNull read validity only (total, never null), and the NaN probes IsNan / IsNotNan test a numeric cell for the IEEE NaN value. Unlike the null probes, the NaN probes propagate nulls — a missing cell is neither NaN nor not-NaN, so the result cell is null — and an Int cell is never NaN; a non-numeric operand is a TypeMismatch at evaluation.

    WhenThen

    pub struct WhenThen {
    cond : Expr
    }

    First step of the conditional chain when(cond).then(a).otherwise(b) — holds the Bool condition until then supplies the matching branch. Constructible only through when (a pub fn cannot return a priv type, so the builder is pub like the Expr variants it carries); its field is read-only outside the package.

    WhenThen::then

    fn WhenThen::then(self : WhenThen, value : Expr) -> WhenThenElse

    Supply the branch taken where the condition is true.

    WhenThenElse

    pub struct WhenThenElse {
    cond : Expr
    then_value : Expr
    }

    Second step of the conditional chain — condition plus then branch, waiting for otherwise to complete the expression. Same read-only rationale as WhenThen.

    WhenThenElse::otherwise

    fn WhenThenElse::otherwise(self : WhenThenElse, value : Expr) -> Expr

    Supply the branch taken where the condition is false, completing the conditional as a Ternary expression node.

    col

    fn col(name : String) -> Expr

    Free-function alias of Expr::col, for the Polars-style call shape col("a") + col("b") (the same static-method + free-alias double export the facade uses for read_csv).

    cols

    fn cols(names : Array[String]) -> Array[Expr]

    Build a column-reference list from names: cols(["a", "b"]) is exactly [col("a"), col("b")]. The ergonomic shorthand for the common case of projecting (or dropping) several existing columns by name through the expression verbs — df.select(cols(["a", "b"])) reads almost like the names-only projection it replaces. Each name resolves at evaluation time, exactly like col; building the list is total.

    lit

    Free-function alias of Expr::lit.

    lit_bool

    fn lit_bool(value : Bool) -> Expr

    Bool literal.

    lit_float

    fn lit_float(value : Double) -> Expr

    Float literal.

    lit_int

    fn lit_int(value : Int64) -> Expr

    Int literal (64-bit, like every MoonFrame integer cell).

    lit_series

    fn lit_series(series :
    Series
    ) -> Expr

    Embed a pre-materialised Series as a literal column, so a ready-made column joins a pipeline beside the declarative col(...) ... expressions (df.with_columns([lit_series(s), (col("a") + col("b")).with_alias("c")])). At evaluation the series is used as-is: a length-1 series broadcasts over the evaluation height (like a scalar lit), a series whose length matches the frame supplies one cell per row, and any other length raises LengthMismatch. The result column keeps the series' own name unless with_alias overrides it — so with_columns([lit_series(s)]) adds, or in-place replaces, a column named s.name(). A free function (the argument is a Series, not an Expr), like the lit_* family and map_many. Building the node is total; the length check happens at evaluation, in frame.

    lit_str

    fn lit_str(value : String) -> Expr

    String literal.

    map_many

    Apply a host closure across several input columns, row by row — the multi-input escape hatch, and the reified replacement for the v0.1 closure filter predicate: f is handed one @types.Scalar per input in inputs order (null cells as Scalar::Null) and is called for every row, so a row predicate is map_many(..., f). returning a Bool. A free function rather than a method (there is no single self); inputs may mix columns, literals, and aggregations, the length-1 results broadcasting over the row count. Same opacity, totality, dtype inference, naming (after the leftmost input), and value-barrier rules as map_elements. The inputs array is copied, so mutating it after construction cannot alter the built expression.

    when

    fn when(cond : Expr) -> WhenThen

    Open a conditional expression: when(cond).then(a).otherwise(b) evaluates to a where cond is true, b where it is false, and null where cond is null. The chain is the only construction route, so a conditional is complete by the time it becomes an Expr.