Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

for each over containers

for each works the same way over the standard library's containers as over an array: it declares the loop variable, visits every element, and ends with a plain next. The basic forms over arrays are on the for each page; this page shows what each container yields.

#import "std/containers"

'' Every library container can be walked with for each.
dim primes as containers.Array( of int32 ) = { 2, 3, 5, 7 }
print "primes:";
for each p in primes
    print p;
next
print

'' byref binds the element itself, so the loop can change it.
for each byref p in primes
    p *= 10
next
print "times ten:"; primes[0]; primes[3]

'' A set yields its members; an ordered one, in sorted order.
dim tags as containers.OrderedSet( of ustring )
tags.Add( "red" ) : tags.Add( "blue" ) : tags.Add( "red" )
print "tags:";
for each tag in tags
    print " "; tag;
next
print

'' A map yields key/value records...
dim ages as containers.OrderedMap( of ustring, int32 )
ages.Put( "grace", 85 )
ages.Put( "ada", 36 )
ages.Put( "edsger", 72 )
for each entry in ages
    print entry.key; " is"; entry.value
next

'' ...and Pairs( ) yields tuples, which for each takes apart.
for each (who, age) in ages.Pairs( )
    print who; "="; str( age ); " ";
next
print

Output

primes: 2 3 5 7
times ten: 20 70
tags: blue red
ada is 36
edsger is 72
grace is 85
ada=36 edsger=72 grace=85 
Containerfor each yields
Array( of T )each T, in index order
OrderedSet( of T )each member, in sorted order, each once
OrderedMap( of K, V )a record with fields key and value, in key order
.Pairs( ) of a mapa (key, value) tuple, ready to destructure

for each byref p binds the element itself, so p *= 10 changes the array. Without byref the loop variable is a copy. A container whose iterator hands out copies refuses byref: over an OrderedMap it is TKO0818: 'for each byref' needs a byref Value( ).

for each (who, age) in ages.Pairs( ) declares one variable per element of each tuple. The names are copies, and the list form takes neither as nor byref.

The plain Map and Set are walked the same way, but in an order you must not depend on. Use the ordered versions when the order is part of the output. Containers covers each one.

Activities

  1. Walk ages.Keys( ), an Array of the keys, and print each key.
  2. Add 1 to every age. for each byref over the map is refused, so walk ages.Keys( ) and write through ages[ k ].