CS 330 Lecture 25 – Currying and The One-Liner
Agenda
- what ?s
- what does this do?
- the Maybe/Option type
- currying and how to read Haskell function specifications
- find’ in an association list/hash
- point-free style
- foldl and foldr
- or’
- and’
- sum’
- product’
- min’
- foldr1′
- max’
- join’
- length’
- average’
- map’
- countOvers
- composing functions
- any’
- all’
TODO
- Play. And homework.
What Does This Do?
char *mystrcpy(char *dst, const char *src) { for (; *src != '\0'; ++src, ++dst) { *dst = *src; } } int main(int argc, char **argv) { char s[1024] = "Bucephalus"; mystrcpy(&s[1], s); printf("%s\n", s); return 0; }
public static <T, U> List<U> foo(List<T> lot, Apply<T, U> f) { List<U> lou = new LinkedList<U>(); for (T t : lot) { lou.add(f.func(t)); } return lou; }
Code
today.hs
-- find' :: [(String, Integer)] -> String -> Maybe Integer
find' [] needle = Nothing
find' (first:rest) needle
| (fst first) == needle = Just (snd first)
| otherwise = find' rest needle
ageBook = [("Sevy", 21), ("Chris", 32)]
getAge name =
case find' ageBook name of Nothing -> "no such person"
Just age -> "this person is " ++ show age
cs330AgeBook = find' ageBook
-- getAge name =
-- case find' ageBook name of Nothing -> error "No such person"
-- Just age -> age
foldr' mix accum [] = accum
foldr' mix accum (first:rest) = mix first (foldr' mix accum rest)
-- and' list = foldr' (\item accum -> accum && item) True list
-- or' list = foldr' (\item accum -> accum || item) False list
and' = foldr' (&&) True
or' = foldr' (||) False
sum' = foldr' (+) 0
product' = foldr' (*) 1
reverse' = foldr' (:) []
Haiku
Got groceries once
Supper was bowls of flour
“You forgot the eggs”
Supper was bowls of flour
“You forgot the eggs”