CS 330 Lecture 30 – Pattern Matching, Partial Function Evaluation, and Map
Agenda
- what ?s
- more on pattern matching
-
capitalize
-
proportionalize
-
at
, a subscript operation
-
- partial function evaluation
-
kthSmallest
-
winner
-
runnerUp
-
- the map pattern
Intentions
- I can organize my solution to a problem by matching my data against patterns in case statements or function parameters.
- I can generate functions from other functions by partially applying a subset of their parameters.
- I can transform one list to another without writing the same old traversal code again and again.
Program This
Write proportionalize, a function that accepts a list of percentages in [0, 100] and converts them to proportions in [0, 1].
Code
Hello.hs
import Data.Char
import Data.List
capitalize :: [Char] -> [Char]
capitalize s =
if s == [] then
[]
else
toUpper (head s) : capitalize (tail s)
capitalize2 s
| s == [] = []
| otherwise = toUpper (head s) : capitalize2 (tail s)
capitalize3 s =
case s of
[] -> []
(first:rest) -> toUpper first : capitalize3 rest
-- ---------------------------------------------------------------------------
capitalize4 [] = []
capitalize4 (first:rest) = toUpper first : capitalize4 rest
-- ---------------------------------------------------------------------------
proportionalize [] = []
proportionalize (first:rest) = first / 100 : proportionalize rest
-- ---------------------------------------------------------------------------
at :: Int -> [t] -> t
-- at 0 [] = error "index oob"
at 0 (first:_) = first
at n [] = error "index oob"
at n (_:rest) = at (n - 1) rest
-- ---------------------------------------------------------------------------
kthSmallest :: (Ord t) => Int -> [t] -> t
kthSmallest k items = at k (sort items)
-- winner items = kthSmallest 0 items
winner :: (Ord t) => [t] -> t
winner = kthSmallest 0
runnerUp :: (Ord t) => [t] -> t
runnerUp = kthSmallest 1
-- ---------------------------------------------------------------------------
map' xform [] = []
map' xform (first:rest) = xform first : map' xform rest
-- proportionalize [] = []
-- proportionalize (first:rest) = first / 100 : proportionalize rest
Haiku
how many loops are there?
My loop spun through days
When grandma’s stopped, mine slowed down
I guess we’re all gears
My loop spun through days
When grandma’s stopped, mine slowed down
I guess we’re all gears