Tuple
A tuple is a group of elements. To store 2 or more pieces of information, a tuple can be used. Each part can be named and given a type.
With a tuple, we have an immutable collection of elements of any type. All the items can have the same type, but this is not required.
In tuples we often encounter the terms "packing" and unpacking. We pack values into a tuple. Here we place the values "cat," 100 and 4 into a single tuple element.
// Create a tuple with three items. // ... It has a string and 2 ints. let data = ("cat", 100, 4) printfn "%A" data // Unpack the tuple into 3 variables. let (animal, weight, feet) = data printfn "%A" animal printfn "%A" weight printfn "%A" feet("cat", 100, 4) "cat" 100 4
With tuples we can return multiple values from a function. Here the testFunction
uses a match construct. And it returns tuples.
// This function returns a tuple with the argument and its English word. // ... It uses a match construct. let testFunction x = match x with | 0 -> (0, "zero") | 1 -> (1, "one") | _ -> (-1, "unknown") // Test the function with three values. let result0 = testFunction 0 printfn "%A" result0 let result1 = testFunction 1 printfn "%A" result1 let result2 = testFunction 2 printfn "%A" result2(0, "zero") (1, "one") (-1, "unknown")
Sometimes we want to assign a name to one item in a tuple. We can use the underscore "_" to ignore parts of a tuple. These cannot be referenced again.
string
) is ignored.// This tuple contains two items. let info = (10, "bird") // Unpack the tuple, but ignore the second item. // ... Use an underscore to ignore it. let (size, _) = info printfn "%d" size10
With tuples, we have small, easy-to-declare collections. For more complex objects, a class
(declared with the type keyword) is appropriate. Tuples are good for return values.
They are a way to group some values of any types together. Unlike a list, the items in a tuple can have different types. We can return tuples from functions.