Tuples in F#
For those of you that are familiar with some of the language extensions
available in C# 3.0, C#'s anonymous types are its implementation of the concept
of tuples. For those of you that aren't, no worries, tuples are very simple.
In mathematics, a tuple is simply a sequence of objects, each of a specific
type. In computer science, tuples are implemented as a very simple but useful
data structure. For instance, lets say we had the following data we'd like to
store:
School: Ohio University
Mascot: Bobcat
Year founded: 1804
Using F#, we could create a tuple grouping this data together like this:
>let mySchool = ("Ohio University", "Bobcat", 1804);;
When we enter this into the Interactive we get the inferred type information:
val mySchool : string * string * int
So our value mySchool is now bound to a tuple of type string * string * int. A
tuple with three items in it is referred to as a triple. Some of the other terms
are single, double, quadruple, etc... Or if you had a tuple with n items in it,
you could just say n-tuple.
Tuples are very useful for returning multiple values from functions, here's an
example of how that might work:
>let getSchool =
let schoolname = "Ohio University" in
let mascot = "Bobcat" in
let year = 1804 in
(schoolname, mascot, year);;
If you wanted to get your values out of your tuple you could use patterns (more
on these later) like this:
>let x,y,z = getSchool;;
Now the identifiers x,y,z are mapped to their respective values contained in the
tuple. If we did this:
>x;;
We'd see that x is now bound to the string "Ohio University".