Home
F#
Tuple Examples
Updated Dec 10, 2022
Dot Net Perls
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.
Tuple notes. 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.
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.
// 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
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
// 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")
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.
// 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
10
A summary. 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 is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen