map
and filter
Some common iterative program patterns:
For each x in L : convert x to y
let f_to_c f = 5. *. (f –. 32.) /. 9.
map f_to_c [-40. ; 32. ; 99.; 212. ]
map float_of_string ["-40" ; "32" ; "99" ]
For each x in L: if x is a foo, add it to list bar
Notice: no explicit recursion in the Ocaml versions
map
Apply a function to every element of a collection, creating a new collection of the results:
let f_to_c f = 5. *. (f –. 32.) / 9.
map f_to_c [-40. ; 32. ; 99.; 212. ]
map float_of_string ["-40" ; "32" ; "99" ]
map Char.lowercase (explode "IT’S HAPPENING!!1!")
Based on these examples, what is the type of map
?
map : ('a -> 'b) -> 'a list -> 'b list
Write your own implementation of map
:
map : (’a -> ’b) -> ’a list -> ’b list
More examples:
make_caps : char list -> char list
first_letters : string list -> char list
“Find all of the items that are…”
What is the type of filter
?
What is the Ocaml implementation of filter
?
Write a function to remove all punctuation from a char list
:
Write a function to exclude all strings that contain '
or -
:
cs2041.org