On this page
lists
02 Lists
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
| Lists | Tuples |
|---|---|
| Sequence of elements of the same type | Finite sequence of components of possibly different types |
Type: [T] | Type: (T1, T2, ..., Tn) |
| Length: The number of elements | Arity: The number of components |
| Lists of same type can have different lengths | All tuples of same type have same arity |
Structure and Operators
Some information required for the next part:
- The empty list is called
niland 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 listtail: return list except the head elementinit: return list except the last elementlast: return last element of a list (non-empty)null: check if list is emptylength: get number of elements in the listfilter: remove elements if they do not fulfill a conditionmap: transform elements with a given function