typestar

Tuples in F#

Pair values without ceremony; patterns take them apart.

// Tuples pair values without ceremony; patterns take them apart.
let coordinates = (52.74, 0.39)
let lat, lon = coordinates
printfn "Apiary at %.2f N, %.2f E" lat lon

// fst and snd read pairs; functions can return them.
let weighAndCount () = (31.4, 18)
let weight, frames = weighAndCount ()
printfn "%.1f kg over %d frames" weight frames

// Underscore discards what you do not need.
let _, framesOnly = weighAndCount ()
printfn "Frames alone: %d" framesOnly
printfn "First of pair: %.2f" (fst coordinates)

How it works

  1. let lat, lon = coordinates destructures in one line.
  2. Functions return tuples for free multiple results.
  3. fst, snd, and _ cover the quick accesses.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
510
Tokens
71
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 3 of 3 in Types, step 15 of 27 in Language basics.

← Previous Next →

Tuples in other languages