Lecture 5-2
Lists
A list contains any number of items that all have the same type.
[1, 2, 3, 4, 5]
['a', 'b', 'c', 'd', 'e']
Lists are built with []
as opposed to tuples which are built with()
.
-
A list can have any number of elements including 0.
[] [1] [1, 2]
-
In Haskell lists are linked lists:
- This means that random access is expensive.
- Internally Haskell will walk the entire list to get to the last element.
Strings
In Haskell strings are just a list of characters. This means that ['a', 'b', 'c']
is equivalent to "abc"
. This has the result of allowing any string operator to also work on lists.
Operators
- You can join lists together with the
++
operator, provided that they have the same type. - The
!!
operator gets a specified element from the list.-
Lists are zero indexed.
> [1 ,2 ,3] !! 0 > 1
-
head
takes the first element of a list.tail
takes all but the first element of the list.-
:
or the cons operator glues a new head onto an existing list.> 1 : [2, 3, 4, 5] > [1, 2, 3, 4, 5]
- Any list can be built by consing onto an empty list.
> 'a' : 'b' : 'c' : [] > "abc"
last
gives the last element of the list.init
gives all elements but the last element.length
returns the number of elements in the list
See the slides for more functions.
Pattern Matching Example
triple_head (x:xs) = 3 * x
This will name the head of the list x
and the tail xs
as the input is x
consed onto xs
.
- It is common for the head to be called
x
or another value and for the tail to be calledxs
with ans
on the tail. - If the pattern cannot be matched, such as if the list is empty, then you will get an error.
-
The wildcard pattern
_
won’t assign a letter if you don’t care about a value.f (_:y:_) = 3 * y
Exercises
-
thricesum list = sum list * 3
-
thirdelement _:_:x:_ = x
-
exclaim string = '!':string:'!'