Fsharp: tuple
originally ai generated
what is tuple
A tuple is
- fixed-length
- ordered collection of values
- can have different types
Tuple is 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
let person = ("Alice", 30, true) let name, age, isActive = person printfn "%s is %d years old" name age // Alice is 30 years old
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
note, there's no builtin function for third, etc.
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:
- Temporary grouping of a small, fixed number of values (2–4 items).
- Returning multiple results from functions.
- Pattern matching is very natural with tuples.
Limitations: Not suitable for large or variable-sized data (use lists/arrays instead).
struct tuple
there is also a “struct tuple”
// normal tuple let xx = (123, "abc") // type is printfn "%A" (xx.GetType()) // System.Tuple`2[System.Int32,System.String] (* The 2 means the arity of the tuple. *) // compare self printfn "%b" (obj.ReferenceEquals(xx, xx)) // true // s------------------------------ // struct tuple let yy = struct (123, "abc") // type is printfn "%A" (yy.GetType()) // System.ValueTuple`2[System.Int32,System.String] // compare self printfn "%b" (obj.ReferenceEquals(yy, yy)) // false