Tuples in F#

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Tuples in F#

  1. A Person Trying To Sharpen His Programming with F# Everyday says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: