Docsity

Lecture Notes on Pattern Matching in Haskell for CPSC 326 (Spring 2013), Study notes of Programming Languages

Partial preview of the text

Download Lecture Notes on Pattern Matching in Haskell for CPSC 326 (Spring 2013) and more Study notes Programming Languages in PDF only on Docsity!

Today ...

  • Quiz 4
  • Pattern matching in Haskell

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?

  • xs empty ... return ys
  • ys empty ... return xs
  • neither empty ... return else expression

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

Wildcards

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

  • stands for any value
  • corresponding value cannot be accessed on RHS
  • helps readability ... focuses attention on the important stuff
  • again, use wildcards in your homework!

Guards

Patterns specify “coarse” conditions for matching

  • Matching on parts of a structure

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)

  • We can rewrite this using using patterns with guards:

myDrop n xs | n <= 0 = xs myDrop _ [] = [] myDrop n (_:xs) = myDrop (n-1) xs

  • The guard gives a condition for applying the pattern

There can be multiple guards per pattern

letterGrade p | p >= 90 = "A" | p >= 80 = "B" | p >= 70 = "C" | p >= 60 = "D" | otherwise = "F"

  • Each guard is an expression of type Bool
  • otherwise is a special variable bound to True

How a guard works

  • For each pattern, check if first guard succeeds
  • If so, RHS is result
  • Otherwise, check next guard
  • If no guards succeed, go to the next pattern

When calling a function, if no patterns match ...

  • Haskell gives a runtime exception (non-exhaustive pattern)