Docsity

Recursion - Organization of Programming Languages - Lecture Notes, Study notes of Programming Languages

Partial preview of the text

Download Recursion - Organization of Programming Languages - Lecture Notes and more Study notes Programming Languages in PDF only on Docsity!

Today ...

  • Occurs check
  • More on recursion
  • Pattern matching in Haskell

Homework

  • HW 3 due, Reading 4 due
  • HW 4 out, Reading 5 out

The Occurs Check Error

Q: How can we define flatten in Haskell?

flatten xs = if null xs then xs -- this doesn’t work! else head xs ++ flatten (tail xs)

Q: What is the type of flatten?

  1. xs must be a list since we call null xs so: [?] ->?
  2. head xs a list since we use ++ on it so: [[a]] ->?
  3. result must have same type as head xs so: [[a]] -> [a]
  4. but result must be same type as xs (from then xs) so: [a] ≡ [[a]]
  5. repeating this out gives [[[ · · · a · · · ]]] infinite type!

Q: How can we fix this?

flatten :: [[a]] -> [a] flatten xs = if null xs then [] -- this works! else head xs ++ flatten (tail xs)

Q: Why does this work?

Q: How can we change minL to behave better?

minL’ xs = if null (tail xs) then head xs else let m = minL’ (tail xs) in if head xs <= m then head xs else m

Or using where instead:

minL’ xs = if null (tail xs) || head xs <= m then head xs else m where m = minL’ (tail xs)

Another Example of Recursion

Binary search is a classic example of recursion ...

  • We’ll use quot for “integer division” (e.g., 3 quot 2 ⇒ 1)
  • We’ll also use (!!) for list index (e.g., xs !! 0 returns first elem)

binSearch :: Ord a => a -> [a] -> Bool binSearch x ys = if null ys then False else if x == midval then True else if x < midval then binSearch x (take mid ys) else binSearch x (drop (mid+1) ys) where mid = (length ys) quot 2 midval = ys !! mid

  • Note: Better off doing linear search here ... why?
    • Because (!!) is a recursive function (and so O(n))
    • Alternatively, can use arrays

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

The mix function defined using patterns

mix2 [] ys = ys mix2 xs [] = xs mix2 xs ys = head xs : head ys : mix2 (tail xs) (tail ys)