





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






Today ...
Questions on HW 3 or the Final?
Pattern Matching: A more involved example with lists ...
mix1 xs ys = if null xs || null ys then xs ++ ys else head xs : head ys : mix1 (tail xs) (tail ys)
Q: What do the following return?
mix1 [] [] ==> []
mix1 [1,3,5] [] ==> [1,3,5]
mix1 [] [2,4,6] ==> [2,4,6]
mix1 [1,3,5] [2,4,6] ==> [1,2,3,4,5,6]
Q: What are the patterns?
Another (simpler) example ...
f xs = head xs
is the same as
f (x:xs) = x
And:
g xs = tail xs
is the same as
g (x:xs) = xs
Use the “wildcard” symbol ( ) for “don’t care”
For example:
f (x:_) = x -- don’t care about tail of the list
g (_:xs) = xs -- don’t care about head of the list
fst (x, _) = x -- don’t care about second elem of pair
snd (_, y) = y -- don’t care about first elem of pair
Patterns specify “coarse” conditions for matching
Guards allow us to define conditions for a pattern
-- old myDrop function myDrop n xs = if n <= 0 || null xs then xs else myDrop (n-1) (tail xs)
myDrop n xs | n <= 0 = xs myDrop _ [] = [] myDrop n (_:xs) = myDrop (n-1) xs
There can be multiple guards per pattern
letterGrade p | p >= 90 = "A" | p >= 80 = "B" | p >= 70 = "C" | p >= 60 = "D" | otherwise = "F"
How a guard works
When calling a function, if no patterns match ...