CS 330 Lecture 26 – More Folding, Composing, Custom Data Types
Agenda
- more folding: join, length, map, find, filter
- folding on 1+ lists: min, max
- composing: countOvers, any, all
- custom data types: an expression hierarchy
- making something an Ord
TODO
- Read chapter 9 through section 9.2.2. Quarter sheet.
Code
today.hs
find' [] needle = Nothing
find' (first:rest) needle
| (fst first) == needle = Just (snd first)
| otherwise = find' rest needle
foldr' mix accum [] = accum
foldr' mix accum (first:rest) = mix first (foldr' mix accum rest)
and' = foldr' (&&) True
or' = foldr' (||) False
sum' = foldr' (+) 0
product' = foldr' (*) 1
join' = foldr' (++) []
join'' = foldr' (++) ""
length' = foldr' (\item accum -> 1 + accum) 0
average' l = sum' l / length' l
map' xform = foldr' (\item accum -> xform item:accum) []
filter' predicate = foldr' (\item accum -> if predicate item then item:accum else accum) []
-- countOvers threshold los = length' (filter' (\s -> length' s > threshold) los)
countOvers threshold = length' . filter' (\s -> length' s > threshold)
data Expr = Add Expr Expr
| Subtract Expr Expr
| Negate Expr
| Literal Double
| Variable String
deriving (Show)
evaluate (Add e1 e2) = evaluate e1 + evaluate e2
evaluate (Subtract e1 e2) = evaluate e1 - evaluate e2
evaluate (Negate e) = -1 * evaluate e
evaluate (Literal d) = d
evaluate (Variable name) = error "I'm not there yet. :("
data LineSegment = LineSegment Double Double Double Double deriving (Show, Eq)
data Vowel = A | E | I | O | U deriving (Bounded, Show)
seglen (LineSegment x1 y1 x2 y2) = sqrt ((x2 - x1) ^ 2 + (y2 - y1) ^ 2)
instance Ord LineSegment where
compare s1 s2 = compare (seglen s1) (seglen s2)
Haiku
Numbers fell on me
Not numbers… Meters… Seconds…
Types grounded physics
Not numbers… Meters… Seconds…
Types grounded physics