Iteration & Loops
Most loops in Nomi are calls to Iter
functions such as Iter.map,
Iter.filter and
Iter.reduce, as in the last few chapters. For a
loop that carries a value from one round to the next, use
Iter.loop.
This chapter also covers break, continue and return inside the functions
you pass to these calls, and recursion.
Loops with Iter.loop
Section titled “Loops with Iter.loop”Iter.loop runs a loop that carries a value, its state, from one round to
the next. Here are two loops, a countdown and a search through Fibonacci
numbers:
fn main()
// Countdown: break when n reaches 0.
countdown = Iter.loop(5, fn n ->
if n == 0 then break
n - 1
end)
dbg countdown
// Tuple state: the first Fibonacci pair whose second number is over 100.
(a, b) = Iter.loop((0, 1), fn (x, y) ->
if y > 100 then break (x, y)
(y, x + y)
end)
dbg a
dbg b
enddbg line 8: countdown = 0
dbg line 16: a = 89
dbg line 17: b = 144
Iter.loop calls the function you give it again and again. The function’s
parameter is the loop’s state, and the value before the function is the
starting state. In the countdown, n starts at 5.
Each round, the function returns the state for the next round. A bare break
ends the loop with the current state as its result. break value ends it with
value, which has the same type as the state.
The state is a single value. To carry more than one thing, use a tuple or a struct. The Fibonacci loop carries a pair, and its parameter is a pattern that takes the pair apart.
continue ends the round early and starts the next one with the same state.
Unless the round did something outside the loop, such as reading a line of
input, the next round does exactly the same thing, and the loop never ends.
A loop with nothing to carry takes no parameter: Iter.loop(fn -> ...). It
ends with a bare break, and its result is Unit. Writing break 0 in such a
loop is a compile error. To end with a value, give the loop a state and break
with that.
This loop prints the lines it reads until it reads quit or runs out of
input. continue skips a blank line and goes on to read the next one:
import std::io
fn main()
Iter.loop(fn ->
Ok(Some(line)) = io.read_line() else break
if line == "" then continue
if line == "quit" then break
io.print(line)
end)
end
Ok(Some(line)) = io.read_line() else break binds line when the read
gives a line, and runs the else otherwise
(Binding with else).
The loop’s body can also be a named function: Iter.loop(5, step) calls
step with 5 in the first round.
Keeping every step with Iter.scan
Section titled “Keeping every step with Iter.scan”Iter.reduce gives back only the final total.
Iter.scan gives back the total after each
element. Like Iter.map, it is lazy: it computes each total only when
something asks for it. Its starting value comes before the function, as a
loop’s does:
fn main()
running =
[3, 1, 4, 1, 5]
|> Iter.scan(0, fn total, x -> total + x)
|> Iter.to_list()
dbg running
enddbg line 7: running = [3, 4, 8, 9, 14]
The starting value itself is not in the output, so there is one total per
element. When each element should produce its own result while a value is
carried along, use Iter.map_reduce. Its
function returns (next_state, result), the state first as it takes it, and
the call gives back the final state and the list of results.
break and continue in iter callbacks
Section titled “break and continue in iter callbacks”Inside a callback you pass to an Iter function, you can use break to
stop early and continue to skip an element:
fn main()
// break in reduce: stop adding once the total would pass 60.
partial_sum =
[10, 20, 30, 40, 50]
|> Iter.reduce(0, fn acc, x ->
if acc + x > 60 then break
acc + x
end)
dbg partial_sum
// continue in map: leave odd numbers out of the output.
evens_doubled =
[1, 2, 3, 4, 5]
|> Iter.map(fn x ->
if x % 2 != 0 then continue
x * 2
end)
|> Iter.to_list()
dbg evens_doubled
enddbg line 10: partial_sum = 60
dbg line 21: evens_doubled = [4, 8]
The reduce stops when adding 40 would take the total past 60, and gives back
the total so far. The map skips the odd numbers.
continue skips the current element. map leaves it out of the output,
and reduce keeps the total as it was.
break stops the iteration and gives back what has been built so far.
reduce gives the total so far, map and filter give the items so far,
Iter.loop gives the current state, and each gives Unit.
break value uses value as the result for this element, then stops. In
reduce, value is the final total. In map, it is the last item of the
output. In filter, break True keeps this element and break False drops
it.
Fine print
- Only these functions’ callbacks take
breakandcontinue:Iter.map,scan,filter,take_while,drop_while,flat_map,iterate,reduce,map_reduce,each,find,any_match,all_match,Iter.loop,Map.map_valuesandMap.map_keys. In any other lambda they are an error. continuetakes no value. To carry a new value forward, make it the callback’s result.- A bare
breakinfind,any_matchandall_matchreturnsNone,FalseandTrue. - A
deferin a callback runs at the end of each round, before the next one starts.
Spec: Callbacks that take break and continue,
break and continue.
Helper functions that break or continue
Section titled “Helper functions that break or continue”return, break and continue each leave only the function they are
written in. None of them can jump past that function into the one that called
it.
return valuehandsvalueback to the function’s caller.break,break valueandcontinuehand a signal back to theIterfunction that called the callback. That function then stops or skips the element.
A named function can use break and continue too. They act on the
iteration you pass the function to. Pass the function itself as the callback,
as in Iter.map(keep_small).
A named function passed to a fold comes after the starting value, as with
Iter.loop:
fn keep_small(x: Int) -> Int
if x > 100 then continue
x
end
fn add_until_zero(total: Int, x: Int) -> Int
if x == 0 then break
total + x
end
fn main()
small =
[5, 500, 7]
|> Iter.map(keep_small)
|> Iter.to_list()
dbg small
total =
[1, 2, 0, 4]
|> Iter.reduce(0, add_until_zero)
dbg total
enddbg line 17: small = [5, 7]
dbg line 23: total = 3
keep_small’s continue leaves 500 out of the list. add_until_zero’s
break stops the reduction when it reaches the 0, and reduce gives back the
total so far, 3.
You can’t call a function that uses break or continue. Its signal would
have to pass through the function that called it to reach the iteration, and
a signal leaves only one function. This holds even when the call is the whole
body of a lambda, so this is a compile error:
fn add_until_zero(total: Int, x: Int) -> Int
if x == 0 then break
total + x
end
fn main()
total =
[1, 2, 0, 4]
|> Iter.reduce(0, fn total, x -> add_until_zero(total, x))
dbg total
endmain.nomi:9:42: `add_until_zero` uses `break`, so it cannot be called: pass it as an iteration callback itself, as in `Iter.reduce(xs, <start>, add_until_zero)`
main.nomi:9:42: help: to decide in this callback instead, return a `Maybe` or an enum from `add_until_zero` and write `break` here
When you want a helper to decide and the callback to act, have the helper
return a Maybe (or an enum), and write the continue in the callback:
fn small(x: Int) -> Maybe<Int>
if x > 100 then None else Some(x)
end
fn main()
doubled =
[5, 500, 7]
|> Iter.map(fn x ->
Some(n) = small(x) else continue
n * 2
end)
|> Iter.to_list()
dbg doubled
enddbg line 14: doubled = [10, 14]
small gives None for 500. The callback skips that element with its own
continue and doubles the others.
return inside a lambda
Section titled “return inside a lambda”return inside a lambda leaves that lambda, not the function the lambda is
written in:
fn main()
mapped =
[1, 2, 3, 4, 5]
|> Iter.map(fn x ->
if x == 3 then return 300
x * 10
end)
|> Iter.to_list()
dbg mapped
enddbg line 10: mapped = [10, 20, 300, 40, 50]
In a callback, return value makes value the result for this element, and
the iteration moves on to the next one. Here map puts 300 where 30 would
have gone. A bare return gives Unit.
? follows the same rule. Inside a lambda, a ? that fails returns from
the lambda.
A lambda can’t return from the function it is written in. To stop a whole
iteration because of something a callback saw, break from the callback and
check the result afterwards.
Fine print
- A
returnin a nestedfnor aconcurrentblock also belongs to that inner boundary. - A bare
returnas the last statement does nothing, and is an error:this `return` does nothing. - A statement after a
return,break,continueorunreachablecan never run, and is an error. So is one after anIter.loopwith nobreak.
Spec: Returning.
Recursion and tail calls
Section titled “Recursion and tail calls”A function may call itself. Recursion fits a problem that breaks into a smaller copy of itself, such as counting the digits of a number:
fn digits(n: Int) -> Int
if n < 10 then 1 else 1 + digits(n / 10)
end
fn sum_to(n: Int, total: Int) -> Int
if n == 0 then total else sum_to(n - 1, total + n)
end
fn main()
dbg digits(2026)
dbg sum_to(200_000, 0)
enddbg line 10: digits(2026) = 4
dbg line 11: sum_to(200_000, 0) = 20000100000
A call is a tail call when its result is the function’s result, with
nothing left to do after it. sum_to ends in a tail call. Nomi runs a tail
call in place of the caller, so it uses no extra memory however many times
it repeats. Carrying the running total as a parameter is what makes the
call a tail call.
digits adds 1 after its call returns, so each call waits for the next.
At most 100,000 calls can wait at once. One more stops the program with
stack overflow: more than 100000 nested calls. digits never gets near
that, but a call like it that walks 200,000 steps would.
For a loop over a collection, the Iter functions are still the first
choice. Recursion is for steps that Iter doesn’t describe well.
Fine print
- A tail call is the last expression of a body, either branch of an
ifor any arm of acasein tail position, the last stage of a pipe, the operand ofreturn, and the right side ofandandor. - A call inside a lambda is in the lambda’s tail position, not the outer
function’s. A default and the operand of
?are never in tail position. - A pending
defercancels a tail call, so recursion that defers each round keeps a frame per round. - Each task has its own 100,000-call limit.
- A function that always calls itself with the arguments it was given is a
compile error:
every path through grow calls grow(x) with the arguments it was given, so it never returns.
How iteration works in Nomi
Section titled “How iteration works in Nomi”Iteration is built from three pieces:
- The
Iterinterface. A type implements one function,each_while, which hands each element to a callback until the callback returnsFalse. Then everyIterfunction (map,filter,reduce,take_while,find,countand the rest) works on that type. Two more functions are optional. A type that knows how many elements it has can say so withknown_count. A type that never ends can say so withis_infinite, and thenIter.to_list,Iter.countand the other functions that need every element stop with an error instead of running forever. Iter.loop, for any loop with its own state and stopping rule.- Pipes, which chain
Iter.filter,Iter.take_while,Iter.reduceand the rest into whatever steps you need.
The standard library uses the same pieces you do. Collections have no map of
their own that builds a new list right away. To get a list, you write
Iter.map(xs, f) |> Iter.to_list().
break and continue are ordinary returns that carry a signal, so stopping
early costs little.
See it in action
Section titled “See it in action”Every example that uses Iteration & Loops
Next: Structs, Enums, Distinct Types, where you declare your own data types.