Tuples
Key points
Types constructed from literal values
Anonymous types, but aliases can be defined to give them a name
Product types by definition
Hence the
*sign in the type signature:A * B
Number of elements in the tuples:
π 2 or 3 (
A * B * C)β οΈ > 3 : possible but prefer Record
Order of elements is important
If
AβB, thenA * BβB * A
Construction
Syntax of literals: a,b or a, b or (a, b)
Comma
,: symbol dedicated to tuples in F#Spaces
are optionalParentheses
()may be necessary
β οΈ Pitfall: the symbol used is different for literals vs types
,for literal*for signatureE.g.
true, 1.2βbool * float
Deconstruction
π Same syntax as construction
β οΈ All elements must appear in the deconstruction
β Use _ (discard) to ignore one of the elements
Tuples in practice
Use cases
Use a tuple for a data structure:
Small: 2 to 3 elements
Light: no need for element names
Local: small scope
Tuples are immutable: β modifications are made by creating a new tuple
Structural equality
Structural equality works by default, but only between 2 tuples of the same signature:
Nesting
Tuples can be nested in bigger tuples using parentheses ()
Pattern matching
Patterns recognized with tuples:
β Notes:
Patterns are ordered from specific to generic
The last pattern
x, yis the default one to deconstruct a tuple
Pairs
2-element tuples
So common that 2 helpers are associated with them:
fstas first to extract the 1st element of the pairsndas second to extract the 2nd element of the pairβ οΈ Only works for pairs
πΉοΈ Quiz
1. Implement fst and snd
2. What is the signature of this function?
Last updated
Was this helpful?