Slides-11-haskell
Slides-11-haskell
deriv :: (Float->Float)->Float->Float
deriv f x = (f(x+dx) - f x)/0.0001
2/32
Currying Revisited
3/32
Currying Revisited. . .
4/32
Currying Revisited. . .
5/32
Currying Revisited. . .
6/32
Patterns of Computation
Mappings
Apply a function f to the elements of a list L to make a new
list L′ . Example: Double the elements of an integer list.
Selections
Extract those elements from a list L that satisfy a predicate p
into a new list L′ . Example: Extract the even elements from
an integer list.
Folds
Combine the elements of a list L into a single element using a
binary function f . Example: Sum up the elements in an
integer list.
7/32
The map Function
8/32
The map Function. . .
inc x = x + 1
map
[2,3,4,5]
9/32
The map Function. . .
10/32
The map Function. . .
Simulation:
11/32
The filter Function
12/32
The filter Function. . .
13/32
The filter Function. . .
filter :: (a->Bool)->[a]->[a]
filter [] = []
even [1,2,3,4]
filter p (x:xs)
| p x = x : filter p xs
| otherwise = filter p xs f
[even 1, even 2,
i
even 3, even 4]
l
filter even [1,2,3,4] ⇒ [2,4] t
[False, True,
e
False, True] r
[2,4]
14/32
The filter Function. . .
doublePos [1,2,3,4] ⇒
map dbl (filter pos [1,2,3,4]) ⇒
map dbl [2,4] ⇒ [4,8]
15/32
fold Functions
sum [1,2,3,4,5] ≡
(1 + (2 + (3 + (4 + (5 + 0))))) ⇒ 15
concat ["H","i","!"] ≡
("H" ++ ("i" ++ ("!" ++ ""))) ⇒ "Hi!"
16/32
fold Functions. . .
foldr:
17/32
fold Functions. . .
? or [True,False,False] ⇒
foldr (||) False [True,False,False] ⇒
True || (False || (False || False)) ⇒ True
18/32
fold Functions. . .
In general:
foldl(⊕)z[x1 · · · xn ] = (((z ⊕ x1 ) ⊕ x2 ) ⊕ · · · ⊕ xn )
19/32
fold Functions. . .
foldl(⊕)z[x1 · · · xn ] = foldr(⊕)z[x1 · · · xn ]
20/32
fold Functions. . .
⊕ ⊕
x1 ⊕
⊕ xn
x2 ⊕
⊕ x3
x3
⊕ x2
⊕
xn z x1
z
foldr ⊕ z [x1 · · · xn ] foldl ⊕ z [x1 · · · xn ]
21/32
Operator Sections
(*2) 4 = 4 * 2 = 8
(>2) 4 = 4 > 2 = True
(++ "\n") "Bart" = "Bart" ++ "\n"
22/32
Operator Sections. . .
(a op) b = a op b
Examples:
(+1) – The successor function.
(/2) – The halving function.
(:[]) – The function that turns an element into a singleton
list.
More Examples:
24/32
takeWhile & dropWhile. . .
25/32
takeWhile & dropWhile. . .
26/32
Summary
27/32
Summary. . .
Exercise (a):
Define the map function using a list comprehension.
Template:
map f x = [ · · · | · · · ]
Exercise (b):
Use map to define a function lengthall xss which takes a
list of strings xss as argument and returns a list of their
lengths as result.
Examples:
29/32
Exercise
mystery xs =
foldr (++) [] (map sing xs)
sing x = [x]
Examples:
minimum [3,4,1,5,6,3] ⇒ 1
30/32
Exercise. . .
31/32
Exercise
32/32