1 / 10

Haskell

Haskell. Chapter 4. Recursion. Like other languages Base case Recursive call Author programs a number of built-in functions as examples. Maximum. maximum' :: ( Ord a) => [a] -> a maximum' [] = error "can't take maximum of empty list“ -- base case, if only one item, return it

mercury
Download Presentation

Haskell

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Haskell Chapter 4

  2. Recursion • Like other languages • Base case • Recursive call • Author programs a number of built-in functions as examples

  3. Maximum maximum' :: (Ord a) => [a] -> a maximum' [] = error "can't take maximum of empty list“ -- base case, if only one item, return it maximum' [x] = x -- else return max of first element or recursive call maximum' (x:xs) = max x (maximum' xs)

  4. Replicate replicate' :: Int -> a -> [a] replicate' n x -- base case returns empty list | n <= 0 = [] -- else cons element to result of recursive call | otherwise = x : replicate' (n-1) x • Used guards because boolean condition, not a pattern • replicate' 3 5 • 5 : replicate’ 2 5 => [5,5,5] • 5 : replicate’ 1 5 => [5, 5] • 5: replicate’ 0 5 => [5] • n == 0, => []

  5. Take • Two base cases (n=0, or empty list) • Guard without otherwise will fall through to patterns take' :: (Num i, Ord i) => i -> [a] -> [a] take' n _ | n <= 0 = [] take' _ [] = [] take' n (x:xs) = x : take' (n-1) xs

  6. Reverse • Note ++ rather than : because both are lists • : works at front of list, not back reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = reverse' xs ++ [x]

  7. Repeat • Haskell supports infinite lists repeat' :: a -> [a] repeat' x = x:repeat' x • repeat 3 • 3: repeat 3 • 3: repeat 3 • etc,

  8. Zip zip' :: [a] -> [b] -> [(a,b)] zip' _ [] = [] zip' [] _ = [] zip' (x:xs) (y:ys) = (x,y):zip' xsys

  9. Quick Exercise • With a partner, trace this code with this list of numbers: • [5,2,6,7,1,3,9,4] quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = let smallerOrEqual = [a | a <- xs, a <= x] larger = [a | a <- xs, a > x] in quicksortsmallerOrEqual ++ [x] ++ quicksort larger Turn in for class participation credit

  10. Play and Share? • No, let’s start on the homework.

More Related