Tuples
Prerequisites: Functions
A tuple groups a fixed number of values, possibly of different types, separated by commas:
let point = (3, 4)
let person = ("Ada", 36, true)
printfn "%A" point
printfn "%A" person
let (x, y) = point
printfn "x=%d y=%d" x y
let (name, _, _) = person
printfn "%s" name
printfn "%d %d" (fst point) (snd point)
(3, 4)
("Ada", 36, true)
x=3 y=4
Ada
3 4
- The type of
personisstring * int * bool— the*separates the element types. let (x, y) = pointdestructures the tuple;_ignores an element.fstandsndwork on pairs (two-element tuples) only.
Returning several values
Tuples are the easy way to return more than one result:
let divide a b = (a / b, a % b)
let (quotient, remainder) = divide 17 5
printfn "17 / 5 = %d remainder %d" quotient remainder
let minMax list = (List.min list, List.max list)
let (lo, hi) = minMax [4; 9; 1; 7]
printfn "%d..%d" lo hi
17 / 5 = 3 remainder 2
1..9
.NET methods that return a tuple
.NET TryParse methods have an "out" parameter. F# turns it into a
tuple of "did it work" and the value:
let (ok, number) = System.Int32.TryParse "123"
printfn "%b %d" ok number
let (ok2, _) = System.Int32.TryParse "abc"
printfn "%b" ok2
true 123
false
When to use tuples
Tuples are great for small, short-lived groupings — two or three values
returned from a function or passed through a pipeline. When the values
have meanings worth naming ("name", "age", "email"), use a record
instead (Level 2): person.Age is clearer than the second element of a
tuple.