Fsharp: tuple

By Xah Lee. Date: .

ai answer

A tuple is a fixed-size, ordered collection of values that can have different types. Tuples are value types (structs) and are useful for returning multiple values from a function without defining a custom record or class.

Creating Tuples

// Tuple of two integers
let point2D = (10, 20)
printfn "%A" point2D
// (10, 20)
// Tuple with mixed types
let person = ("Alice", 30, true)  // string * int * bool
printfn "%A" person
// ("Alice", 30, true)
// Nested tuple
let complex = ((1, 2), (3, 4))
printfn "%A" complex
// ((1, 2), (3, 4))

Accessing Tuple Elements

let point2D = (10, 20)
let x, y = point2D
printfn "%d %d" x y
// 10 20

Using fst and snd (only for pairs)

// Using fst and snd (only for pairs)
let point2D = (10, 20)
let x = fst point2D
let y = snd point2D
printfn "%d" x
// 10
printfn "%d" y
// 20
let person = ("Alice", 30, true)
let name, age, isActive = person
printfn "%s is %d years old" name age
// Alice is 30 years old

Common Operations

// Swap elements

let point2D = (10, 20)

// define a swap function
let swap (a, b) = (b, a)

printfn "%A" (swap point2D)
// (20, 10)
// Return multiple values from a function
let divide x y =
    if y = 0 then None
    else Some (x / y, x % y)  // tuple inside Option
// Tuple as function parameter
// let add (a, b) = a + b

When to use tuples:

Limitations: Not suitable for large or variable-sized data (use lists/arrays instead).

Reference

fsharp data structure