After the ground types int, float, string, bool and unit, we get interested in composite types.
- Remember what is a cartesian product? The set ℤ×ℤ contains pairs of two integers, such as (3, 8).
The set ℝ×ℤ×ℕ contains triples such as (1.5, -12, 40). - In OCaml, tuples (cartesian products) are built-in. Just check the types of the following expressions:
(2, 4) ;;
(1.5, "ok") ;;
(false, true, -10) ;;
( (), true, () ) ;;
The parentheses are not always necessary: 2, 4 ;;
- Note that
(1, 2, 3)
is not equivalent to (1, (2,3))
(compare both types). - Functions are really first-class citizens:
let add = (+) ;;
(add, abs) ;;
It is a pair of functions (having different types).Exercise : Tuples
- Guess the types of:
( 0 < 1, false) ;;
( add, add 1, add 1 2) ;;
- What happens with
(1,2) + (3,4)
?
- Tuples can be used to define several variables at once:
let (a,b,c) = (100, 200, 300)
let (myplus, myminus) = ( (+), (-) )
These two lines define five variables a, b, c, myplus, myminus