Lists
As a first example of recursion, we will study Haskell’s built-in datatype for lists.
List syntax
A list is a sequence of an arbitrary number of elements of some type. For instance, seasons
is a list of strings:
seasons :: [String] seasons = ["spring","summer","fall","winter"]
The signature shows that the list type is written as two square brackets, [ and ], with the type of elements between them. In the case of seasons, the element type is String
. The equation of seasons shows that a list value is written as a comma-separated list of elements between square brackets.
As the notation suggests, the list type is parametric in its element type. For example, redSuits
is a list of Suits
:
redSuits :: [Suit] redSuits = [Hearts,Diamonds]
This uses the Suit
datatype from the previous chapter.
A special case of a list is an empty list – for example, of Bool
elements:
noBools :: [Bool] noBools = []
Another...