Heroes / Esempi / 04-loops

examples/gallery/04-loops.hero

Due modi per ripetere operazioni, con un segno esplicito per ogni modifica a un valore.

while ripete le operazioni finché una condizione è vera e for scorre una sequenza. Ogni assegnazione che modifica un valore richiede un segno esplicito, così puoi individuare le righe in cui lo stato del programma cambia.

Eseguilo

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

Questo esempio serve a illustrare il linguaggio. Qui trovi il programma e non un risultato: non ci sono ancora test che confrontino il suo output byte per byte.

Il programma

## 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 righe

impronta sha256 cce336c59d1f · 1 file · index.json

Successivo: 05-mutation. Tutti gli esempi. ← Precedente: 03-fallible

Eseguine uno: i quattro comandi. Impara il linguaggio, oppure leggi la specifica completa in un solo file.