A programming language designer should be responsible for the mistakes made by programmers using the language. It is a serious activity; not one that should be given to programmers with 9 months experience with assembly; they should have a strong scientific basis, a good deal of ingenuity and invention and control of detail, and a clear objective that the programs written by people using the language would be correct, free of obvious errors and free of syntactical traps.
— Tony Hoare, Null References: The Billion Dollar Mistake, 2009
https://www.infoq.com/presentations/ Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/
©D. Poole 2021
CPSC 312 — Lecture 5 1/9
Announcements
Assignment 1 solution available. Assignment 2 available.
CPSC 312 — Lecture 5 2/9
©D. Poole 2021
Review
Haskell Types:
Bool (&&, ||, not) Num (+, −, ∗, abs)
Integral (div, mod) Int
Integer Fractional (/)
Floating (log, sin, exp, …) Double
Eq (==, /=)
Ord (>, >=, <=, <)
List ([] 🙂 Char
String tuples
CPSC 312 — Lecture 5 3/9
©D. Poole 2021
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 4/9
©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 5/9
©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
(zip v1 v2)
CPSC 312 — Lecture 5 9/9
©D. Poole 2021