C.8 Tuples

A tuple is a sequence of elements of potentially mixed types. Formally, a tuple is an element e of a Cartesian product of a given number of sets: e ∈ (S1 × S2 × … × Sn). A two-element tuple is called a pair [e.g., e ∈ (A × B)]. A three-element tuple is called a triple [e.g., e ∈ (A × B × C)]. A tuple typically contains unordered, heterogeneous elements akin to a struct in C with the exception that a tuple is indexed by numbers (like a list) rather than by field names (like a struct). While tuples can be heterogeneous, in a list of tuples, each tuple in the list must be of the same type. Elements of a pair (i.e., a 2-tuple) are accessible with the functions fst and snd:

A set of two code lines in Haskell for making elements of a pair accessible with different functions.
Description
Continuation of the code in Haskell for making elements of a pair accessible with different functions, consisting of six lines.
Description

The response from the interpreter when :type (1, "Mary", 3.76) is entered (line 7) is (1, "Mary", 3.76) :: (Fractional c, Num a) => (a, [Char], c) (line 8). The expression (Fractional c, Num a) => (a, [Char], c) is a qualified type. Recall that the a means “any type” and is called a type variable; the same holds for type c in this example. The expression (1, "Mary", 3.76) :: (Fractional c, Num a) => (a, [Char], c) (line 8) indicates that if type c is in the class Fractional and type a is in the class Num, then the tuple (1,"Mary",3.76) has type (a,[Char],c). In other words, the tuple (1,"Mary",3.76) consists of an instance of type a, a list of Characters, and an instance of type c.

The right-hand side of the response from the interpreter when a tuple is entered [e.g., (a, [Char], c)] demonstrates that a tuple is an element of a Cartesian product of a given number of sets. Here, the comma (,) is the analog of the Cartesian-product operator ×, and the data types a, [Char], and c are the sets involved in the Cartesian product. In other words, (a, [Char], c) is a type defined by the Cartesian product of the set of all instances of type a, where a is a member of the Num class; the set of all lists of type Char;and the set of all instances of type c, where c is a member of the Fractional class. An element of the Cartesian product of the set of all instances of type a, where a is a member of the Num class; the set of all lists of type Char; and the set of all instances of type c, where c is a member of the Fractional class, has the type (a, [Char], c):

A code line in Haskell.
Description

The argument list of a function in Haskell, described in Section C.9, is a tuple. Therefore, Haskell uses tuples to specify the domain of a function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.22.145