C.7 Lists

The following are some important points about lists in Haskell.

  • Lists in Haskell, unlike in Scheme, are homogeneous, meaning all elements of the list must be of the same type. For instance, the list [1, 2, 3] in Haskell is homogeneous, while the list (1 "apple") in Scheme is heterogeneous.

  • In a type-safe language like Haskell, the values in a tuple (Section C.8) generally have different types, but the number of elements in the tuple must be fixed. Conversely, the values of a list must all have the same type, but the number of elements in the list is not fixed.

  • The semantics of lexeme [] is the empty list.

  • The cons operator, which accepts an element (the head) and a list (the tail), is : (e.g., 1:2: [3]) and associates right-to-left.

  • The expression x:xs represents a list of at least one element.

  • The expression xs is pronounced exes.

  • The expression x:[] represents a list of exactly one element, just as [x] does.

  • The expression x:y:xs represents a list of at least two elements.

  • The expression x:y:[] represents a list of exactly two elements.

  • The functions head and tail are the Haskell analogs of the Scheme functions car and cdr, respectively.

  • The element selection operator (!!) on a list uses zero-based indexing. For example, [1, 2, 3, 4, 5]!!3 returns 4.

  • The built-in function len returns the number of elements in its only list argument.

  • The append operator (++) accepts two lists and appends them to each other. For example, [1, 2]++[3, 4, 5]; returns [1, 2, 3, 4, 5]). The append operator in Haskell is also inefficient, just as it is in Scheme.

  • The built-in function elem is a list member and returns True if its first argument is a member of its second list argument and False otherwise.

Examples:

A set of 33 code lines in Haskell consisting of lists.
Description

As can be seen, in Haskell a String is a list of Chars.

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

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