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 and struct tuple.
normally, it means reference tuple.
Creating tuples
// 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))
Accessing 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
Using fst and snd (only for 2-tuple)
// 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
note, there's no builtin function for third, etc.
Common operations
// Swap elements let xx = (10, 20) // define a swap function let swap (a, b) = (b, a) printfn "%A" (swap xx) // (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
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