4 - Lists
Published online by Cambridge University Press: 05 November 2014
Summary
Lists are the workhorses of functional programming. They can be used to fetch and carry data from one function to another; they can be taken apart, rearranged and combined with other lists to make new lists. Lists of numbers can be summed and multiplied; lists of characters can be read and printed; and so on. The list of useful operations on lists is a long one. This chapter describes some of the operations that occur most frequently, though one particularly important class will be introduced only in Chapter 6.
List notation
As we have seen, the type [a] denotes lists of elements of type a. The empty list is denoted by []. We can have lists over any type but we cannot mix different types in the same list. As examples,
[undefined,undefined] :: [a]
[sin, cos, tan] :: Floating a ⇒ [a → a]
[[1,2,3],[4,5]] :: Num a ⇒ [[a]]
[“tea”, “for”, 2] not valid
List notation, such as [1,2,3], is in fact an abbreviation for a more basic form
1:2:3:[]
The operator (:) :: a → [a] → [a], pronounced ‘cons’, is a constructor for lists. It associates to the right so there is no need for parentheses in the above expression. It has no associated definition, which is why it is a constructor. In other words, there are no rules for simplifying an expression such as 1:2:[].
- Type
- Chapter
- Information
- Thinking Functionally with Haskell , pp. 63 - 88Publisher: Cambridge University PressPrint publication year: 2014