Containers
A fixed array holds as many elements as its declaration says. Most collections
are not like that: a list grows as items arrive, a word count gains a key for
every new word, a set of visited cells answers "have I been here?" again and
again. The std/containers module has a collection for each of those jobs.
#import "std/containers"
dim words( 0 to 7 ) as ustring = _
{ "red", "blue", "red", "green", "blue", "red", "teal", "green" }
'' Three containers, three questions about the same words.
dim order as containers.Array( of ustring ) '' all of them, in order
dim seen as containers.Set( of ustring ) '' each one once
dim counts as containers.Map( of ustring, int32 ) '' how many of each
for each w in words
order.Push( w )
if seen.Add( w ) then print "new word: "; w
counts[ w ] += 1
next
print order.Count( ); " words,"; seen.Count( ); " distinct"
print "the fifth word is "; order[ 4 ]
'' A Map has no order of its own, so sort the keys before printing.
var keys = counts.Keys( )
containers.Sort( keys )
for each k in keys
print k; ":"; counts[ k ]
next
Output
new word: red
new word: blue
new word: green
new word: teal
8 words, 4 distinct
the fifth word is blue
blue: 2
green: 2
red: 3
teal: 1
#import "std/containers" brings in the module, and its types are named
through it: containers.Array( of ustring ). Each container is a generic type,
so you choose the element type when you declare one, and each works with
for each.
| Container | Holds | Good at |
|---|---|---|
Array( of T ) | elements in order, by index from 0 | appending, walking, indexing |
Map( of K, V ) | a value for each key | finding a value by its key |
Set( of T ) | each value at most once | "is it in?", set operations |
OrderedMap, OrderedSet | keys kept sorted | order, nearest key |
LinkedList( of T ) | elements in a chain | adding and removing at both ends |
Deque( of T ) | elements in a ring | both ends, and by index |
PriorityQueue( of T ) | elements by priority | taking the smallest next |
BitSet | small numbers, one bit each | flags, sets of indices |
The rest of the section covers sorting, searching, rearranging, keys of your own and brace-list initialisers.
Copying a container copies every element in it, so pass containers to
procedures byref, as the examples in this section do.
Activities
- Print the words in the order they first appeared, using
seen.Addto skip repeats. - Print the most frequent word and its count.