Lecture 10 (Missed last lec)

3 Fundamental patterns of recursion

  1. Accumulation (aka folding)

  2. Transformaiton (aka mapping)

  3. Selection (aka filtering)

Selection

Write a function that removes all occurrences of x from a list

E.g remove 3 [1,2,3,4] === [1,2,4]

remove :: Int -> [Int] -> [Int]
remove x [] = []
remove x (y:ys)   = 
      | x == y    = (remove x ys)
      | otherwise = y : (remove x ys)

Insertion Sort

General Recursion

  • No longer follows the nice primitive recursion outline

Example:

Implementation

zip (x:xs) (y:ys) = (x,y):(zip xs ys)
zip _ _           = []
  • Case analysis is very important

nth_elm :: Int -> [Int] -> Int
nth_elm 0 (x:_) = x
nth_elm n (_:xs)
   | n > 0      = nth_elm (n-1) xs
   |