Skip to content

types: Numeric bound for arithmetic, and sum - #274

Merged
vito merged 4 commits into
ordered-type-paramsfrom
numeric-constraint
Nov 10, 2026
Merged

vito merged 4 commits into
ordered-type-paramsfrom
numeric-constraint

Conversation

@vito

@vito vito commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Adds Numeric, a second built-in constraint for type parameters, and the sum list method bounded by it. Users can now write their own numeric folds:

mySum[a: Numeric](xs: [a!]!, zero: a!): a! { xs.reduce(zero) { acc, x => acc + x } }
mean[a: Numeric](xs: [a!]!): Float! { xs.reduce(0.0) { acc, x => acc + x } / xs.length }
abs[a: Ordered & Numeric](x: a!): a! { if (x < 0) { -x } else { x } }

mySum([1, 2, 3], 0)       # 6
mySum([0.5, 0.25], 0.0)   # 0.75
[1, 2, 3].sum             # 6
["a"].sum                 # error: cannot sum a list of String!: it is not a number; Numeric types are Int! and Float!

sum replaces the BuiltinDef.ElemTypes / Select.listElemType hook that #263 had and dropped. It goes through #272's constraint table instead, the same way sort uses Ordered.

Wiring

  • The constraint. Numeric is a new BuiltinConstraint entry in constraints.go: name, predicate whyNotNumeric, and the operators addition, subtraction, multiplication, division and modulo. Its members are exactly Int! and Float!. Like Ordered, the bound ignores nullability. Bound parsing, the "constraint, not a type" error and the unknown-bound list (known bounds: Numeric, Ordered) all pick it up from the table.
  • Arithmetic. resolveOperands asks resolveNumericVars first. When an operand is a rigid variable bounded by Numeric, only the numeric meaning applies, so + doesn't concatenate strings or lists. Unary minus accepts a bounded a! too.
  • Comparisons. checkConstrainedOperands mixes a Numeric a! with numbers the way arithmetic does (numbersMix), so [a: Ordered & Numeric] can write x < 0.
  • sum. Method(ListTypeModule, "sum").Returns(NumericVar('a')): the bound on the element variable goes through boundedElems, like sort's. So any other list, [Int]! included, is an error at the call, and a deferred element type (let xs = []; xs.sum; xs += ["a"]) fails where it's learned.

Maintainer decisions

  1. Result types follow the numbers.
    • a! op a! and a! op Int! (either way round) are a!. Int op Int is Int and Float op Int is Float, so it's sound, and / is Int division when a is Int, as it is without generics.
    • a! op Float! is Float!.
    • Two different Numeric parameters (a! + b!) are an error, because one could be Int and the other Float.
  2. Numeric doesn't imply Ordered. Comparing needs [a: Ordered & Numeric]. The hint keeps the bounds the variable already has: declare it [a: Numeric & Ordered].
  3. Hints. Arithmetic or unary minus on an unbounded variable now says declare it [a: Numeric]. The exceptions are a string or list operand ("n=" + x) and an unbounded operand beside a Numeric one, where the bound wouldn't help. Two pre-existing goldens (arithmetic_on_generic_type, generic_annotation_escapes_rigid) now carry the hint.
  4. Empty sum uses the runtime element type. An empty list sums to 0.0 when the list is known to hold Floats at runtime (float literals, an annotated [], a list passed for a [Float!]! parameter, or one filtered or sliced from those) and to 0 otherwise. To keep that through generic code, list materialization now keeps the list's own ElemType when the target is generic ([a!]!) instead of overwriting it with the variable. This touches every list passed to a generic parameter, not only for sum. Still 0 while typed Float!: a [] typed only by its surroundings (xs ?? [], an if branch, a reduce([]) accumulator) and a list built inside a generic body (xs.map { x => x * 2 } there). This is documented on the collections page and in the skill; dang: empty collections carry their inferred type #278 (stacked above) fixes these cases at the root.

Open question (answered: Q-27, option C)

An empty sum could produce an Int value in a Float! slot here. The maintainer picked option C: fix the root cause. That fix is #278, stacked on this PR: empty []/[:] literals and lists built inside generic bodies now carry their inferred element type at runtime, so an empty Float! sum is 0.0 in the cases above. With #278, the "still 0" caveat in decision 4 narrows to a type variable that a generic call's arguments don't decide.

Tests and docs

  • tests/test_numeric.dang: a user-written sum, mean, scale, halve, rem, negation, +=, Ordered & Numeric (sort plus add, abs).
  • tests/test_list_sum.dang: Int and Float lists, derived lists, generic xs.sum, typed empty lists (including through a generic parameter), deferred element types, nullable receivers.
  • Error goldens: sum on [String!]!, on [Int]!, on [Decoded!]! (list_sum_decoded_element), and deferred; arithmetic and negation on an unbounded variable; string concatenation on an unbounded variable (no hint); a nullable bounded a, operand and negation; two Numeric parameters; a Numeric and an unbounded operand; + "s" on a Numeric value; < on Numeric alone; a non-numeric argument at the call.
  • Docs: types/nullability.md (type-params section, retitled "Type parameters, Ordered and Numeric"), data/collections.md (sum), language/operators.md, reference/grammar.md, and the dang-language skill (types, syntax, objects, stdlib, SKILL routing).
  • Checks: pkg/dang, pkg/hm, pkg/lsp, docs/go, tests, docs and fmt/stale pass.

vito added 3 commits November 8, 2026 23:25
Numeric is a second entry in the constraint table: exactly Int! and Float!
(whyNotNumeric), enabling + - * / %. A rigid `a!` bounded by it takes the
arithmetic operators and unary minus, with only the numeric meaning of +.
The result follows the numbers: a! with a! or Int! is a!, anything with
Float! is Float!, and two different Numeric parameters are rejected, since
one may be Int and the other Float. A bare `a` may be null and is refused.
Comparisons mix a Numeric a! with numbers the same way, so
`[a: Ordered & Numeric]` can write `x < 0`.

Arithmetic or unary minus on an unbounded variable now says `declare it
[a: Numeric]` (not beside a string or list, or a Numeric variable, where
the bound wouldn't help), and a variable with other bounds is told to add
the missing one (`[a: Numeric & Ordered]`).

Signed-off-by: Alex Suraci <[email protected]>
`[T]!.sum` adds up a list of Int! or Float!. Its element variable is bounded
by Numeric, like sort's by Ordered, so any other list (nullable elements
included) is an error where it's called, and an element type learned later
is checked where it's learned.

An empty list sums to 0, or 0.0 when its runtime element type is Float. So
that a [Float!]! passed for a generic [a!]! parameter keeps that, list
materialization now keeps the list's own element type when the target's
mentions type variables. A [] typed only by its surroundings (`xs ?? []`)
or a list built in a generic body still carries no concrete element type
at runtime and sums to 0.

Signed-off-by: Alex Suraci <[email protected]>
The type-params section of nullability.md covers Numeric, its result types
and combining it with Ordered; the collections page, operators, grammar and
the dang-language skill cover sum and the new bound.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito added this pull request to stack #273 November 8, 2026 23:26
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Deploying dang with  Cloudflare Pages  Cloudflare Pages

Latest commit: 17d73e2
Status: ✅  Deploy successful!
Preview URL: https://4c2b8c68.dang-3kk.pages.dev
Branch Preview URL: https://numeric-constraint.dang-3kk.pages.dev

View logs

@vito
vito force-pushed the numeric-constraint branch from c7cba4a to 4412195 Compare November 8, 2026 23:56
@vito
vito force-pushed the numeric-constraint branch from 4412195 to 5eb0f1b Compare November 9, 2026 17:38
@vito
vito marked this pull request as ready for review November 9, 2026 17:39
@vito
vito force-pushed the numeric-constraint branch from 5eb0f1b to 9a3168a Compare November 9, 2026 17:42
Pin that .sum over a list of Decoded data is a compile error.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the numeric-constraint branch 3 times, most recently from d4abeea to 17d73e2 Compare November 10, 2026 00:26
@vito
vito merged commit 2335c6a into main Nov 10, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant