Home
Search
Tuple ExamplesLearn the syntax of tuples. Create tuples, unpack tuples and return tuples from methods.
F#
This page was last reviewed on Dec 10, 2022.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.