CSCI 2041

ADVANCED PROGRAMMING PRINCIPLES

List Functions:

map and filter

List functions

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

filter (fun d -> d.temp > 32)
  [ { temp=36 ; wx = CLOUDS } ; { temp = 19 ; wx = SNOW } ]

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

let rec map f l = match l with
| [] -> []
| h::t -> (f h)::(map f t)

More examples:

make_caps : char list -> char list

first_letters : string list -> char list

filtering

“Find all of the items that are…”

filter (fun n -> n mod 2 = 0)
    [1; 1; 2; 3; 5; 8; 13; 21; 34]
filter (fun ch -> ch = '?' || ch = '.')
   (explode "Who... are you? Who? Who? Who? Who?")
filter (fun (h,a,l) -> (h-a) > l)
    [ (27,23,-3) ; (14,13,3) ; (7,21,-1) ]

What is the type of filter?

filter : ('a -> bool) -> 'a list -> 'a list

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

// reveal.js plugins