Heroes / Examples / 04-loops

examples/gallery/04-loops.hero

Repeat work with two kinds of loop and mark each change to a value.

while repeats while a condition is true, and for visits each value in a sequence. Assignments that change a value carry an explicit mark, making it easier to see which lines depend on the order of execution.

Run it

$ heroes run examples/gallery/04-loops.hero

These files introduce the language one feature at a time. This page shows the program and not a result, because no test compares their output byte for byte yet.

The program

## Loops and cells
#
# Two loops, two words: `while cond` while a condition holds, `for x in xs`
# over a sequence. Mutation is the minority of lines and it is marked, so the
# order-dependent part of a program is the part that jumps out.

# The largest element. Fails on nothing: an empty array has no largest, so
# the caller is asked for a floor instead.
function largest_or(xs: [i64], floor: i64) -> i64
    best: i64 @= floor

    for x in xs
        if x > best
            best @ x

    return best

# Sums until the running total would pass a limit, then stops.
function sum_until(xs: [i64], limit: i64) -> i64
    total: i64 @= 0

    for x in xs
        if total + x > limit
            break
        total @ total + x

    return total

# Counts the even ones, and shows `continue` earning its keep.
function even_count(xs: [i64]) -> i64
    seen: i64 @= 0

    for x in xs
        if x % 2 != 0
            continue
        seen @ seen + 1

    return seen

# The conditional loop, with the counter visible: `while cond` has no header
# that hides where the index changes.
function digits_in(n: i64) -> i64
    left: i64 @= n
    digits: i64 @= 1

    while left >= 10
        left @ left / 10
        digits @ digits + 1

    return digits

# The loop variable is not needed, so it is `_` — the same wildcard a pattern
# uses, and the reason an unused name is never an accident here.
function repeat_dash(times: i64) -> str
    out: str @= ""

    for _ in range(from: 0, to: times)
        out @ out + "-"

    return out

test "the four loops"
    assert largest_or([3, 9, 4], 0) == 9
    assert largest_or([], -1) == -1
    assert sum_until([5, 5, 5, 5], 12) == 10
    assert even_count([1, 2, 3, 4]) == 2
    assert digits_in(1004) == 4
    assert repeat_dash(3) == "---"

function main()
    print(repeat_dash(20))
    print("digits in 2026: ", digits_in(2026))
examples/gallery/04-loops.hero, 72 lines

fingerprint sha256 cce336c59d1f · 1 file · index.json

Next: 05-mutation. All the examples. ← Previous: 03-fallible

Run one yourself: the four commands. Learn the language, or read the full specification in one file.