F# Tuple Examples

Learn the syntax of tuples. Create tuples, unpack tuples and return tuples from methods.

Tuple. A starfish has just 5 arms. To store five 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. Tuples are powerful.

First example. 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.

Then: We unpack the tuple's items into 3 variables (animal, weight, feet). We can then address those variables directly.

F# program that uses tuples // 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 Output ("cat", 100, 4) "cat" 100 4

Multiple return values. With tuples we can return multiple values from a function. Here the testFunction uses a match construct. And it returns tuples.Match
F# program that returns tuple from function // 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 Output (0, "zero") (1, "one") (-1, "unknown")

Underscore. 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.

Here: We create a 2-item tuple (a pair) and then set "size" to the first item in the pair. The second item (a string) is ignored.

F# program that uses underscore, tuple // 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" size Output 10

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.

Tuples are useful. 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.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to