Haskell Language List basics


Example

The type constructor for lists in the Haskell Prelude is []. The type declaration for a list holding values of type Int is written as follows:

xs :: [Int]    -- or equivalently, but less conveniently,
xs :: [] Int

Lists in Haskell are homogeneous sequences, which is to say that all elements must be of the same type. Unlike tuples, list type is not affected by length:

[1,2,3]   :: [Int]
[1,2,3,4] :: [Int]

Lists are constructed using two constructors:

  • [] constructs an empty list.

  • (:), pronounced "cons", prepends elements to a list. Consing x (a value of type a) onto xs (a list of values of the same type a) creates a new list, whose head (the first element) is x, and tail (the rest of the elements) is xs.

We can define simple lists as follows:

ys :: [a]
ys = []

xs :: [Int]
xs = 12 : (99 : (37 : []))   
-- or  = 12 : 99 : 37 : []     -- ((:) is right-associative)
-- or  = [12, 99, 37]          -- (syntactic sugar for lists)

Note that (++), which can be used to build lists is defined recursively in terms of (:) and [].