An accumulatorTutorial (draft)AssociativityMappingDocumentation and user's manualTable of contentsOCaml programs

Mapping

   
  Consider the following codes

(** Computes the list of twice each element in a list of integers *)
(* *)
let rec map_twice = function
  li -> if is_empty_list (li) 
          then empty_list ()
          else cons_list (2 * head (li), map_twice (tail (li)))

(** Computes he list of the lengths of the elements in a list of lists *)
(* *)
let rec map_length = function
  llx -> if is_empty_list (llx) 
           then empty_list ()     (* ----- llx : type error ----- *)
           else cons_list (List.length (head (llx)), map_length (tail (llx)))

   
  Look at the definitions of  map_twice  and  map_length . Clearly their structures are similar.

Transform what is identical in them into a functional value (named  map_to_all ) that can be applied to obtain the value of  map_twice  or that of  map_length :

let map_to_all = function
  f -> (let rec g = function
          lx -> if is_empty_list (lx)
                  then empty_list ()
                  else cons_list (f (head (lx)), g (tail (lx)))
        in
          g)

   
  The type of  map_to_all  is

('a -> 'b) -> ('a list -> 'b list)

   
  An example of application of the higher-order function  map_to_all :

(** Computes the list of three times each element in a list of integers *)
(* *)
map_to_all (function x -> 3 * x)

Now an example of application of the result of this application of the higher-order function  map_to_all :

(** Computes the list of three times each element in a list of integers *)
(* *)
(map_to_all (function x -> 3 * x)) ([1 ; 2 ; 3])

   
  Note that  map_to_all  and  List.map  (the function  map  provided by the Objective Caml module  List ) have the same value.

   
  Finally note that the value of  map_to_all  can also be recursively defined:

let rec map_to_all_1 = function
  f -> (function
          lx -> if is_empty_list (lx)
                  then empty_list ()
                  else cons_list (f (head (lx)), (map_to_all_1 (f)) (tail (lx))))


Latest update : October 5, 2006
This document was translated from LaTeX by Hyperlatex 2.5, which is not the latest version of Hyperlatex.

An accumulatorTutorial (draft)AssociativityMappingDocumentation and user's manualTable of contentsOCaml programs