Loops
Kiwi has three loops. Each opens its body with do and closes it with end.
| Loop | Use it for |
|---|---|
for ... in ... do | Walking a list, range, string, hashmap or generator |
while condition do | Repeating until a condition becomes false |
repeat n do | Running a block a fixed number of times |
for iterates over a collection. Add a second variable to get the index (or, for hashmaps, the value).
fruits = ["kiwi", "mango", "lime"]
for fruit in fruits do println fruitend
for fruit, i in fruits do println "${i}: ${fruit}" # 0: kiwi, 1: mango, 2: limeendIt works on every iterable type:
# Ranges count without building a list.for i in [1 to 3] do print "${i} "endprintln "" # 1 2 3
# Strings yield one character at a time.for ch in "abc" do print ch.uppercase()endprintln "" # ABC
# Hashmaps yield keys, or key-value pairs.scores = {alice: 95, bob: 82}for name, score in scores do println "${name} scored ${score}"endGenerators are consumed one value at a time, so a for loop can walk an infinite sequence as long as it breaks out.
while repeats as long as its condition is truthy.
count = 1while count <= 3 do println count count += 1endwhile true do with a break when inside is the idiom for a loop whose exit is in the middle:
attempts = 0while true do attempts += 1 break when attempts >= 3endprintln attempts # 3repeat
Section titled “repeat”repeat n do runs the body n times. as names a counter that runs from 1 to n. A count of zero or less runs nothing.
repeat 2 do println "Hello"end
total = 0repeat 10 as i do total += iendprintln total # 55break and next
Section titled “break and next”break leaves the innermost loop. next skips to the next iteration. Both take an optional when guard, which usually reads better than wrapping them in if.
for n in [1 to 20] do next when n % 3 == 0 # skip multiples of 3 break when n > 10 # stop after 10 print "${n} "endprintln "" # 1 2 4 5 7 8 10In nested loops, break and next affect only the loop they’re in:
for row in [1, 2] do for col in [1, 2, 3] do break when col == 2 print "${row}${col} " endendprintln "" # 11 21Loop variables
Section titled “Loop variables”The loop variable keeps its last value after the loop ends, and variables first assigned in the body stay visible too. See Scoping.
for n in [1, 2, 3] do last = nendprintln last # 3- Prefer
forover index arithmetic withwhile. - Don’t add or remove elements of the list you are iterating; loop over a
.clone()instead. - For transformations, a list method such as
.map,.filteror.reduceis often clearer than a loop. See Lists.