Next: Keyword and default arguments, Previous: Blocks and conditional as expressions, Up: Extensions to C
Tuples are a way to manipulate several values at once.
Creating a new tuple does not allocate memory. Tuples don't have addresses, their content is not placed contiguously in memory. They really are just a way to consider several values at once.
For instance, the tuple (4, 5, 'toto') is a constant. Thus you can create multiple-values constants with L.
When a tuple contain complex expressions (that is to say, anything except a constant or a variable), the order of evaluation is defined to be from the left to the right.
let h = hypot(side1, side2);
calls hypot
with the tuple (side1, side2)
. As a side
effect of the order of evaluation rule stated before, function
arguments are evaluated from left to right. In C, this is undefined,
which causes many portability problems.
let (return_value, is_present) = gethash('key'); let (num_char_scanned, num1_scanned, num2_scanned) = scanf("%d %d");
In most cases, the use of pointers to return several data should be replaced by a multiple return value form. This is one of the example where pointers can be easily avoided in L (thus providing more safety).
In the implementation, the return values are passed in clobbered registers, and is very efficient.
(str,len) = ("foo",4); // same as str = "foo"; len = 4; (point.x, point.y) = (3.0, 5.0); a = 2; b = 3; (a,b) = (b, a); // Now b = 2, and a = 3. let (c,d) = (4, 'foo');
When doing multiple affectations, you can “skip” one by using the special symbol '_':
let i = 0; (a,_,c) = (++i,++i,++i); //a = 1; c=3;
This is most useful when you want to receive values from functions:
(value, present) = gethash(key, hash_table); (value, _) = gethash(key, hash_table); value = gethash(key, hash_table);
Finally, on an implementation note, using tuple is higly efficient, because each component of a tuple can be a register.
For instance, the (a,b) = (b,a)
construct may use the efficient
xchg
instruction on CISC machines; It is difficult for a
standard C compiler to use these instructions, and the corresponding
code would use three instructions and a supplementary register.
Tuple is thus an both a pleasant and efficient abstraction.
Note: Depending on the architecture, Word64 can be or not a tuple. But most code can ignore this fact and completly ignore the issue.