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
Parentheses
()
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, y
is the default one to deconstruct a tuple
Pairs
2-element tuples
So common that 2 helpers are associated with them:
fst
as first to extract the 1st element of the pairsnd
as 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?