CurryingTutorial (draft)MappingAn accumulatorDocumentation and user's manualTable of contentsOCaml programs

An accumulator

   
  Consider the following codes

(** Summation of all the integers in a list *)
(* *)
let rec sum_int_list = function
  lx -> if is_empty_list (lx)
          then 0
          else (function x, y -> x + y) (head (lx), sum_int_list (tail (lx)))

(** Product of all the reals in a list *)
(* *)
let rec prod_float_list = function
  lx -> if is_empty_list (lx)
          then 1.
          else (function x, y -> x *. y) (head (lx), prod_float_list (tail (lx)))

(** Logical conjunction of all the booleans in a list *)
(* *)
let rec and_list = function
  lx -> if is_empty_list (lx)
          then true
          else (function x, y -> x & y) (head (lx), and_list (tail (lx)))

   
  Look at the definitions of  sum_int_list ,  prod_float_list  and  and_list . Clearly their structures are similar.

Transform what is identical in them into a functional value (named  accumul_right ) that can be applied to obtain the values of  sum_int_list , of  prod_float_list  and of  and_list  : 

let accumul_right = function
  (op, neutral) -> (let rec f = function
                     lx -> if is_empty_list (lx)
                             then neutral
                             else op (head (lx), f (tail (lx)))
                   in
                     f)

   
  The type of  accumul_right  is

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

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

(** Logical disjunction of all the booleans in a list *)
(* *)
accumul_right ((function x, y -> x or y), false)

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

(** Computes the list of three times each element in a list of integers *)
(* *)
(accumul_right ((function x, y -> x or y), false)) ([2 + 2 = 5 ; 6 - 3 = 9])


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

CurryingTutorial (draft)MappingAn accumulatorDocumentation and user's manualTable of contentsOCaml programs