Returning tuples
A function that has two answers, such as a quotient and a remainder, can
return both at once as a tuple: a group of values written in parentheses.
The result type lists the element types, and return lists the values:
'' A function can return several values at once as a tuple.
function Divide( byval a as int32, byval b as int32 ) as ( int32, int32 )
return ( a \ b, a mod b )
end function
'' var ( a, b ) = takes the tuple apart into new variables.
var ( quotient, remainder ) = Divide( 17, 5 )
print "17 / 5 ="; quotient; " remainder"; remainder
'' The elements can have names, which the caller can use.
function MinMax( values( ) as int32 ) as ( lo as int32, hi as int32 )
dim as int32 lo = values( lbound( values ) ), hi = lo
for each v in values
if v < lo then lo = v
if v > hi then hi = v
next
return ( lo, hi )
end function
dim as int32 readings( 0 to 4 ) = { 14, 9, 21, 17, 3 }
var range = MinMax( readings( ) )
print "lowest"; range.lo; ", highest"; range.hi
'' A tuple can also be assigned to variables that already exist.
dim as int32 q, r
( q, r ) = Divide( 23, 4 )
print "23 / 4 ="; q; " remainder"; r
Output
17 / 5 = 3 remainder 2
lowest 3, highest 21
23 / 4 = 5 remainder 3
var ( quotient, remainder ) = Divide( 17, 5 ) declares two variables and
fills them from the tuple in order. To fill variables that already exist,
leave out var, as the last call does with ( q, r ).
Elements can be named in the result type: ( lo as int32, hi as int32 ). A
caller that keeps the whole tuple in one variable, like range, then reads
range.lo and range.hi. The names are for reading only; the tuple is the
same type as an unnamed ( int32, int32 ).
A tuple is the light-weight choice when the values belong together only for
the moment of the return. When they are passed around together, a named
record type says more. Tuples in general, and
taking them apart in for each, are in
Tuples and Iterators.
Activities
- Write
function Stats( values( ) as int32 ) as ( count as int32, total as int64 )and print both parts. - Swap two variables with
( a, b ) = ( b, a ).