Some Predefined list definitions (Lists2.hs)
[e1..en] is the list of elements from e1 to en (inclusive) [e1,e2..em] is the list of elements from e1 to em, where e2 − e1 gives step size
[e..] is the list of all numbers from e
take n lst
head lst tail lst
lst !! n
lst1 ++ lst2 append lst1 and lst2
sum [a1,a2,..an]=a1+a2+…+an
zip [a1,a2,…,an] [b1,b2,…,bn] = [(a1,b1),(a2,b2),…,(an,bn)] map f [a1,a2,…,an] = [f a1,f a2,…,f an]
first n elements of lst
is the first element of lst is the rest of the list
nth element of lst
CPSC 312 — Lecture 5 1/4
©D. Poole 2021
Lambda
How can we find elements of a list that are less than 3 or greater than 7 (using filter)?
Lambda lets us define a function without giving it a name. \ x -> (x < 3) || (x > 7)
is a function true of numbers less than 3 or greater than 7
filter (\ x -> (x < 3) || (x > 7)) [1..10]
is easy to read and work out what it is saying A definition
foo x = exp
is an abbreviation for
foo = \ x -> exp
foo x y = exp
foo = \ x -> \y -> exp
foo = \ x y -> exp
myadd = \x y -> x+y
is an abbreviation for alsowritten
CPSC 312 — Lecture 5 2/4
©D. Poole 2021
List Comprehensions
In mathematics, what is
{x2 | x ∈ {1,2,3,4,5,6,7}, x mod 2 = 1}
This is written in Haskell as
[x^2 | x <- [1..7], x ‘mod‘ 2 == 1]
“List Comprehension”
List comprehensions can do everything filter and map can do. This can use pattern matching, e.g.,
[x+y | (x,y) <- [(1,2),(4,3),(5,6)]]
[x+y | (x,y) <- [(1,2),(4,3),(5,6)], x