Tuples and Iterators
Two small problems come up in almost every program. A function has two answers
to give, a minimum and a maximum, and a function returns one value. And a loop
over a collection needs an index it does not care about, with bounds to get
wrong. A tuple solves the first, and for each with the iterator protocol
solves the second.
'' One function, two answers: a tuple carries both.
function MinMax( values() as int32 ) as (lo as int32, hi as int32)
var lo = values( lbound( values ) ), hi = lo
for each v in values '' for each needs no index
if v < lo then lo = v
if v > hi then hi = v
next
return (lo, hi)
end function
dim temps( 0 to 4 ) as int32 = { 12, -3, 25, 7, 0 }
'' Take the tuple apart into two new variables...
var (coldest, warmest) = MinMax( temps() )
print "coldest"; coldest; ", warmest"; warmest
'' ...or keep it whole and use its element names.
var range_ = MinMax( temps() )
print "spread:"; range_.hi - range_.lo
Output
coldest-3, warmest 25
spread: 28
MinMax returns (lo as int32, hi as int32), a tuple type, and
return (lo, hi) builds a value of it. The caller can take it apart with
var (coldest, warmest) = ..., which declares two variables, or keep it whole
and reach the elements by the names the function's declaration gave them.
Tuple types and literals themselves are introduced in
Tuples.
Inside MinMax, for each v in values visits every element without an
index. It walks arrays, the library containers, and any type of your own that
follows the iterator protocol.
This section covers:
- Destructuring and swapping:
(a, b) = (b, a). - Named elements: where element names come from, and why they are not part of the type.
- for each over containers: arrays, sets, maps and pairs.
- for each and strings: bytes, characters and words.
- Making a type iterable:
GetIterator,IsValid,Value,MoveNext. - An iterable generic collection: a ring buffer.
- Lazy sequences: elements computed as they are walked.
- Changing a collection while walking it.
Activities
- Make
MinMaxreturn a third element, the number of values, and print it. - Call
MinMaxon an array with a single element. What does it return?