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, then A * B β‰  B * A

Construction

Syntax of literals: a,b or a, b or (a, b)

  • Comma ,: symbol dedicated to tuples in F#

  • Spaces are optional

  • Parentheses () may be necessary

⚠️ Pitfall: the symbol used is different for literals vs types

  • , for literal

  • * for signature

  • E.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 pair

    • snd as second to extract the 2nd element of the pair

    • ⚠️ Only works for pairs

πŸ•ΉοΈ Quiz

1. Implement fst and snd

Answer
  • Tuple deconstruction: (x, y)

  • We discard one element using _ wildcard

  • Functions can be inline

2. What is the signature of this function?

Answer

'a * 'a -> 'a list

  • Returns a list with the 2 elements x and y of the pair

  • The elements are therefore of the same type

  • There is no constraint on this type β†’ generic type 'a

Last updated

Was this helpful?