The idea of this exercise is to use the principle of the map
function to implement algorithms that transform data structures using higher-order functions.
- Using the function
map
from the moduleList
, write a functionwrap : 'a list -> 'a list list
that transforms alist
of elements'a
into a list of singleton lists. For instance,wrap [1;2;3]
is equal to[[1];[2];[3]]
- Consider the definition of the type
tree
given in the prelude. It represents binary trees carrying data items, on its internal nodes, and on its leaves. Write a functiontree_map : ('a -> 'b) -> 'a tree -> 'b tree
such thattree_map f t
yields a tree of the same structure ast
, but with all its data valuesx
replaced byf x
. For example, suppose a functionstring_of_int : int -> string
, that takes an integer and generates the string that represent this integer. Applied totree_map
and a tree of integers (i.e. of typeint tree
), it would yield a tree of strings (i.e. of typestring tree
).
type 'a tree =
Node of 'a tree * 'a * 'a tree
| Leaf of 'a;;
let wrap l =
"Replace this string with your implementation." ;;
let rec tree_map f = function _ ->
"Replace this string with your implementation." ;;