Not logged in. Login

Haskell Tuple Types

Haskell tuple types define cartesian products.

Definition:
Haskell tuple types are created by enclosing two or more simpler types in parentheses.
<tuple-type> ::= "(" <type> "," <type> { "," <type> } ")"

Haskell tuple types may be given names by type synonym declarations, but it is not required.

type Polygon = (Int, Float)

defines an Int × Float cartesian product.

Access:
The individual elements of a tuple are accessed by pattern matching. In function definitions, this looks very much like specifying the elements of the tuple as individual arguments.
num_of_sides :: Polygon -> Int
num_of_sides(n, s) = n
perimeter :: (Int, Float) -> Float
perimeter(n, s) = (fromIntegral n) * s

Pattern matching can also be used within expressions.

interior_angle :: Polygon -> Float
interior_angle p = let (n, _) = p in 180.0 - (360.0 / fromIntegral n)

Simultaneous construction:
Tuples are constructed by simply listing the values for each member in the tuple.
<tuple-expr> ::= "(" <expression> "," <expression> { "," <expression> } ")"
bigsquare :: Polygon = (4, 195.6)
expand_poly :: (Polygon, Float) -> Polygon
expand_poly((n, s), e) = (n, s * e)

Notice the nested pattern matching in the last definition.

Updated Mon Sept. 28 2015, 19:23 by cameron.