CS 330 Lecture 23 – Guards, Tail Recursion, and Higher-order Functions
Agenda
- what ?s
- replicate
- program this
- guards
- tail recursion
- higher-order functions
- map
- filter
- lambda
TODO
- Read http://learnyouahaskell.com/higher-order-functions. Quarter sheet.
Program This
- Write a function isIn that accepts to parameters: a list and an item. It returns true if the item appears in the last and false otherwise.
- Write a function named eachLower that takes a string parameter (a [Char]) and returns a lowercase version of the string. There’s a function toLower in the Data.Char module that converts a single character to lowercase.
Code
today.hs
import Data.Char
replicate' item 0 = []
replicate' item n = item:replicate' item (n - 1)
isIn [] needle = False
-- isIn haystack needle = if head haystack = needle then True else isIn (tail haystack) needle
-- isIn (first:rest) needle = if first = needle then True else isIn rest needle
isIn (first:rest) needle
| first == needle = True
| otherwise = isIn rest needle
-- isIn (first:rest) needle = first == needle || isIn rest needle
eachLower [] = []
eachLower (first:rest) = toLower first:eachLower rest
eachMult10 [] = []
eachMult10 (first:rest) = first * 10:eachMult10 rest
eachDecapitate [] = []
eachDecapitate ((first:_):rest) = first:eachDecapitate rest
map' f [] = []
map' f (first:rest) = f first:map' f rest
eachLower' list = map' toLower list
-- mult10 a = 10 * a
-- eachMult10' list = map' mult10 list
eachMult10' list = map' (\a -> 10 * a) list
-- eachMult10' list = map' (*10) list
eachDecapitate' list = map' head list
filter' f [] = []
filter' f (first:rest)
| f first = first:filter' f rest
| otherwise = filter' f rest
Haiku
First-class citizens?!
First they are denied a name.
Then executed!
First they are denied a name.
Then executed!