Skip to content

Range algebra: union and intersection inside sum (#476) - #567

Merged
godofecht merged 2 commits into
mainfrom
range-algebra
Aug 19, 2026
Merged

godofecht merged 2 commits into
mainfrom
range-algebra

Conversation

@godofecht

@godofecht godofecht commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #476.

What this adds

Two ranges compose with | (union) and & (intersection) inside sum(...):

println(sum(0..1000 step 3 | 0..1000 step 5))   # 233168
println(sum(0..1000 step 3 & 0..1000 step 5))   # 33165

The first line is the whole of Project Euler 1 as one statement. & binds tighter than |, matching the bitwise operators.

How it works

The intersection of two arithmetic progressions is itself an arithmetic progression, found by CRT: the stride is lcm(pa, pb) and the first common element comes from a modular inverse. Union follows from inclusion-exclusion, sum(A) + sum(B) - sum(A & B), so both cases reduce to the closed form #536 already applied to a single range.

Literal bounds fold to one constant at parse time, at any depth. & distributes over | into a union of progressions, then inclusion-exclusion runs over the subsets. Nothing reaches the backend but a literal, and the generated C contains no helper at all.

Runtime bounds lower to a single helper call carrying all six bounds, so each bound expression is evaluated exactly once. The helper works in i64 internally, so the lcm and the modular inverse cannot overflow on the way to an i32 result.

Also fixed

Negative literal bounds now fold. -7 parses as unary minus over a literal rather than as a negative literal, so sum(10..0 step -3) used to fall through to the runtime helper unnecessarily.

Parsing

Range bounds now parse at equality precedence rather than as full expressions, so a trailing | or & reads as range algebra instead of as a bitwise operator on the step. Outside sum(...) both operators keep their bitwise meaning, and sum(0..n - 1 step 2) still subtracts.

Limits, enforced with a message rather than silently

  • Eight ranges when folded: inclusion-exclusion over n ranges has 2^n - 1 terms.
  • One operator between two ranges when a bound is a runtime value. Deeper algebra is a compile error pointing at sum(A) + sum(B) - sum(A & B).
  • Ranges are still not values. They exist only in a for header and a sum argument.
  • The self-hosted flowc front end does not parse sum(range) at all. That is pre-existing from Lower sum(range) to closed-form arithmetic #536, not a regression here; the docs say so and point at FLOW_HOST=python.

Verification

Tests compare against the actual element sets rather than hand-computed constants.

  • tests/unit/test_range_algebra.py (53 tests) builds the sets in Python and compares, including a 400-case randomized sweep over mixed-sign strides and offset starts.
  • tests/integration/test_range_algebra.py compiles a brute-force loop in Flow and sweeps 500 parameter sets against it in the built binary. Also asserts six bounds produce six evaluations, and that a literal expression leaves no helper in the C.
Check Result
pytest tests/ 1649 passed, 6 skipped
./flow test --tier2 --strict 687/687
ruff check src clean
check_doc_links.py all links and fragments resolve
check_doc_coverage.py every feature has a documented home
check_doc_examples.py --check-ledger no new unverified examples

One pre-existing red test, test_gif_flow_encoder.py::test_animation_actually_moves, fails on main too. It is a Pillow deprecation escalated to an error and is unrelated to this change; deselected in the counts above.

Docs

sum had no spec entry at all, so this adds one to §4.3 alongside the new docs/language/ranges.md, which covers ranges, sum, the algebra, the difference identity, and every limit above. All eight of its examples compile and run; the outputs quoted in this description are that page's actual output.

Two ranges compose with `|` and `&` inside `sum(...)`:

    sum(0..1000 step 3 | 0..1000 step 5)   # 233168
    sum(0..1000 step 3 & 0..1000 step 5)   # 33165

The intersection of two arithmetic progressions is itself an arithmetic
progression, found by CRT: the stride is the lcm of the two strides and the
first common element comes from a modular inverse. Union follows from
inclusion-exclusion, sum(A) + sum(B) - sum(A & B), so both reduce to the
closed form that #536 already applied to a single range.

Literal bounds fold to one constant at parse time, at any depth, by
distributing `&` over `|` into a union of progressions and running
inclusion-exclusion over the subsets. Runtime bounds lower to one helper
call carrying all six bounds, so each bound expression is evaluated exactly
once; the helper works in i64 so the lcm and the modular inverse cannot
overflow on the way to an i32 result.

Negative literal bounds now fold too. `-7` is unary minus over a literal, not
a negative literal, so `sum(10..0 step -3)` previously fell through to the
runtime helper.

Range bounds parse at equality precedence rather than as full expressions, so
a following `|` or `&` reads as range algebra instead of as a bitwise
operator on the step. Outside `sum(...)` both operators keep their bitwise
meaning, and `sum(0..n - 1 step 2)` still subtracts.

Limits, stated in the docs and enforced with a message rather than silently:
eight ranges when folded, one operator between two ranges at runtime, and
ranges are still not values.

Tests compare against the actual element sets rather than hand-computed
constants: the unit tests against Python's `set`, the integration tests
against a brute-force loop in compiled Flow over 500 mixed-sign parameter
sets. `sum` had no spec entry at all, so this adds one.

Closes #476
@godofecht
godofecht merged commit 728f9e6 into main Aug 19, 2026
20 checks passed
@godofecht
godofecht deleted the range-algebra branch August 19, 2026 09:43
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.

Add range algebra: set operations (union, intersection, difference) on ranges

1 participant