Fsharp: Tuple
originally ai generated
What is tuple
A tuple is
- ordered collection of values
- values can be different types
- fixed-length
Tuple is useful for:
- Temporary grouping of a small, fixed number of values.
- as function's parameter in one unit.
- Returning multiple results from functions.
Reference tuple and struct tuple
there are 2 types of tuple in fsharp.
- reference tuple:
(a,b,etc) - struct tuple:
struct (a,b,etc)
reference tuple is the recommended, commonly used one.
Create tuple
// Tuple of two integers let xx = (10, 20) printfn "%A" xx // (10, 20)
// Tuple with mixed types let xx = ("Alice", 30, true) // string * int * bool printfn "%A" xx // ("Alice", 30, true)
// Nested tuple let xx = ((1, 2), (3, 4)) printfn "%A" xx // ((1, 2), (3, 4))
Tuple type
let aa = (3, "x") // type is printfn "%A" (aa.GetType()) // System.Tuple`2[System.Int32,System.String] (* The 2 means the arity of the tuple. *)
Get tuple elements
let xx = (10, 20) let x, y = xx printfn "%d %d" x y // 10 20
let xx = ("Alice", 30, true) let name, age, isActive = xx printfn "%s is %d years old" name age // Alice is 30 years old
Pattern matching
let xx = (3,4) // pattern match to get tuple items match xx with | (a, b) -> printfn "%A %A" a b // 3 4
Get first element, second element
fst→ get first elementsnd→ get second element
these are only for 2-tuple. there's no builtin function for third, etc.
// Using fst and snd (only for 2-tuple) let xx = (10, 20) let x = fst xx let y = snd xx printfn "%d" x // 10 printfn "%d" y // 20
Test equality
let aa = (3, "x") let bb = (3, "x") printfn "%b" (aa = bb) // true
Common uses
Tuple as function parameter
// Tuple as function parameter // let add (a, b) = a + b
Return multiple values from a function
// Return multiple values from a function let divide x y = if y = 0 then None else Some (x / y, x % y) // tuple inside Option
Struct tuple
note, struct tuple is far less common, and operations are different from reference tuple. For beginners, skip it.
// 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