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

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:

Activities

  1. Make MinMax return a third element, the number of values, and print it.
  2. Call MinMax on an array with a single element. What does it return?