A list is a sequence of elements of the same type. They are defined by enclosing the type in square brackets ([T]). Values are defined by enclosing them in square brackets separated by commas ([1, 2, 3]).

Lists vs. Tuples

ListsTuples
Sequence of elements of the same typeFinite sequence of components of possibly different types
Type: [T]Type: (T1, T2, ..., Tn)
Length: The number of elementsArity: The number of components
Lists of same type can have different lengthsAll tuples of same type have same arity

Structure and Operators

Some information required for the next part:

  • The empty list is called nil and written as []
  • The cons ((:)) operator takes an element and a list and returns a new list with the element as its new head
  • Cons associates to the right

This means that [1, 2, 3] translates to 1 : (2 : (3 : [])) and that a finite list always ends with an empty list.

Accessing elements can be done by using (!!) (zero-based): [1, 2, 3] !! 0 ~> 1.
Lists can be concatenated with (++): [1, 2] ++ [3, 4] ~> [1, 2, 3, 4]

Pattern Matching

List elements can be matched using pattern matching.

  stdMatch :: Show a => [a] -> String
stdMatch []     = "Matched empty list"
stdMatch (x:xs) = "Matched list with head " ++ show x

ml :: Show a  => [a] -> String
ml [x]         = "Matched list with one element " ++ show x
ml [x, y]      = "Matched list with two elements"
ml (x:[])      = "" -- equivalent to ml [x]
ml (x:y:[])    = "" -- equivalent to ml [x, y]
  

List Functions

  • head: return first element of a list
  • tail: return list except the head element
  • init: return list except the last element
  • last: return last element of a list (non-empty)
  • null: check if list is empty
  • length: get number of elements in the list
  • filter: remove elements if they do not fulfill a condition
  • map: transform elements with a given function