Tuples

A tuple is a fixed-length sequence of values that may have different types. Tuples are constructed by listing their components in parentheses:

(1, "a", 5.4)          // type: (Integer, String, Double)
(True, 42)             // type: (Boolean, Integer)

Unlike lists, tuples cannot grow or shrink, and their element types need not be uniform.

The empty tuple

The empty tuple () (also called unit) has exactly one value, also written (). It serves as the "void" return type for functions that are called only for their side effects:

print :: String -> <Proc> ()

Accessing components

For pairs, the built-in accessor functions are:

fst :: (a, b) -> a (Prelude)

Gives the first element of a pair.

snd :: (a, b) -> b (Prelude)

Gives the second element of a pair.

For longer tuples, use pattern matching:

third (_, _, x) = x

Pattern matching on tuples

Tuples are deconstructed with pattern matching in function arguments, let/do bindings, and match expressions:

toPolarCoordinates (x, y) = (sqrt (x*x + y*y), atan2 y x)

distance p1 p2 =
    let (x1, y1) = p1
        (x2, y2) = p2
        dx = x1 - x2
        dy = y1 - y2
    in sqrt (dx*dx + dy*dy)

Higher-order utilities

curry :: ((a, b) -> <d> c) -> a -> b -> <d> c (Prelude)

Transforms a function taking a pair as a parameter to a function taking two values as a parameter.

uncurry :: (a -> b -> <d> c) -> (a, b) -> <d> c (Prelude)

Transforms a function two values as a parameter to a function taking a pair as a parameter.

uncurry converts a two-argument curried function to one that takes a pair, which is useful when the data is already in tuple form:

map (uncurry (+)) [(1,2), (3,4), (5,6)]   // [3, 7, 11]