Heroes / Examples / 05-mutation

examples/gallery/05-mutation.hero

Change a copy without changing the original value.

After b: [i64] @= a, changing b cannot change a. A function marks an argument it can change with @, both in its declaration and at every call. You can see at the call whether the function may change the value you pass.

Run it

$ heroes run examples/gallery/05-mutation.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

## Copy in, copy out
#
# Every value behaves as an independent copy: after `b = a`, changing `b`
# never changes `a`. Nothing aliases anything. A function that needs to
# change its argument says so with `@`, in the signature and at the call
# site, so a mutating call cannot look like a reading one.

# A cursor over text. Travels through the reader as `@`.
record Reader
    text: str
    pos: i64

function at_end(r: Reader) -> bool
    return r.pos >= r.text.len()

function here(r: Reader) -> u8
    return r.text[r.pos]

# The `@` is the whole signature's news: this one moves.
function advance(@r: Reader)
    r.pos @ r.pos + 1

# Consumes spaces. The caller sees `@r` and knows the reader moved.
function skip_spaces(@r: Reader)
    while !at_end(r) && here(r) == ' '
        advance(@r)

# Reads a run of letters and hands it back, leaving the reader after it.
function word_at(@r: Reader) -> str
    start = r.pos

    while !at_end(r) && here(r) >= 'a' && here(r) <= 'z'
        advance(@r)

    return r.text.slice(from: start, to: r.pos)

test "the reader walks, and the copy does not"
    r: Reader @= Reader(text: "hi there", pos: 0)
    first = word_at(@r)
    skip_spaces(@r)
    second = word_at(@r)
    assert first == "hi"
    assert second == "there"
    assert at_end(r)

test "values are copies"
    a = [1, 2, 3]
    b: [i64] @= a
    b @ b.push(4)
    assert a.len() == 3
    assert b.len() == 4

function main()
    r: Reader @= Reader(text: "one two", pos: 0)
    print(word_at(@r))
examples/gallery/05-mutation.hero, 55 lines

fingerprint sha256 c110fb6e0eb0 · 1 file · index.json

Next: 06-generics. All the examples. ← Previous: 04-loops

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