Tuples in F#
March 11, 2017 1 Comment
Tuples are collections where each element can be of different type. If you have a C# or Python background then you must be familiar with tuples. A tuple can be used to return multiple values from a function without having to declare an object for it.
Here’s a tuple with 5 elements:
let addThreeNumbers x y z = x + y + z let myFirstTuple = (45, "hello world", 5., true, addThreeNumbers)
This tuple has an integer, a string, a float, a boolean and a function in it.
val myFirstTuple : int * string * float * bool * (int -> int -> int -> int) = (45, “hello world”, 5.0, true, )
There’s no index-based way to access a specific element in the tuple. We can get to the elements by naming them as follows:
let myFirstTuple = (45, "hello world", 5., true, addThreeNumbers) let (myInt, myString, myFloat, myBool, myFunc) = myFirstTuple printfn "Integer in the tuple: %i" myInt let myFuncRes = myFunc 1 2 3
The variables declared in (myInt, myString, myFloat, myBool, myFunc) will get the respective values in the tuple:
val myString : string = “hello world”
val myInt : int = 45
val myFunc : (int -> int -> int -> int)
val myFloat : float = 5.0
val myBool : bool = true
val myFuncRes : int = 6
For tuples with 2 elements the special functions fst and snd – first and second – are used to access the elements:
let tupleDouble = ("hello world", true) let greeting = fst tupleDouble let lovesMeLovesMeNot = snd tupleDouble
val tupleDouble : string * bool = (“hello world”, true)
val greeting : string = “hello world”
val lovesMeLovesMeNot : bool = true
View all F# related articles here.
Before reading this article, I didn’t know and couldn’t imagine that a function returning unit could be an element of a tuple as well as of other collection data types.