Today we learn Tuple, as the first data structure of Collections
tuple is a simple data structure that combine elements together. These elements can be different types
(1, 2)
// Triple of strings.
("one", "two", "three")
// Tuple of generic types.
(a, b)
// Tuple that has mixed types.
("one", 1, 2.0)
// Tuple of integer expressions.
(a + 1, b + 1)
let's do some practices
- defining a tuple with 2 elements
let person = ("John", 30)
let (name, age) = person // this is unpack, unpack first element of person to name, second to age
printfn "Name: %s, Age: %d" name age
you can also get the element by fst snd for a tuple with 2 elements like below
let person = ("John", 30)
let name = fst person // "John"
let age = snd person // 30
printfn "Name: %s, Age: %d" name age
- defining a tuple with 3 elements
let point = (3, 4, 5)
let (x, y, z) = point
printfn "Point coordinates: x = %d, y = %d, z = %d" x y z
there is no trd to get third element of tuple with 3 elements
there is no empty tuple, () is not empty tuple, it's more like Null
- ignore element of tuple
let point = (3, 4, 5)
let (x, _, z) = point
printfn "Point coordinates: x = %d, z = %d" x z
the second element 4 will be ignored
- return a tuple in function
let getPersonInfo() = ("John", 30)
let (personName, personAge) = getPersonInfo()
printfn "Person Name: %s, Person Age: %d" personName personAge
- access elements of tuple in match
let print tuple1 =
match tuple1 with
| (a, b) -> printfn "Pair %A %A" a b // %A can format any type
print (1, 2)
print ("John", 30)
Tuples are particularly useful when you need to return multiple values from a function or when you want to combine several values together
Top comments (0)