for_all/exists, map2/fold2, initSome common list programming idioms:
Check if every (some) element of a list has a property:
Combine two lists into one (or fold them together)
for_all and existsfor_all takes a predicate and a list and returns true if all elements in the list satisfy the predicate:
for_all p [1; 2; 3] ≡ (p 1) && (p 2) && (p 3)
exists takes a predicate and a list and returns true if some element in the list satisfies the predicate
exists p [1; 2; 3] ≡ (p 1) || (p 2) || (p 3)
What is the type of for_all and exists?
How are for_all and exists implemented in Ocaml?
Implement all_caps : char list -> bool via for_all:
Implement has_digits : char list -> bool via exists:
map2 and fold_left2map2 combines two lists into one by applying its function argument to elements of both lists in order, so
What about map2 (fun x y -> (x,y)) [1;2;3] ["a";"b";"c"]?
What is the type of map2?
How is it implemented in OCaml?
implement concatlists : string list -> string list -> string list via map2:
fold_left2 folds two lists together by combining the elements of the two lists with the accumulator, so
fold_left2 (fun acc s1 s2 -> acc^s1^s2) "init" ["a"; "b"; "c"] ["x"; "y"; "z"]
≡ (("init" ^ "a"^"x") ^ ("b"^"y")) ^ ("c"^"z")What is the type of fold_left2?
How is fold_left2 implemented in Ocaml?
implement dot : float list -> float list -> float list via fold_left2:
initinit creates a list by applying its second argument to each integer between 0 and its first argument, so:
init 3 ((+) 17) ≡ [(17+0); (17+1); (17+2)]
What is the type of init?
cs2041.org