Date: Fri, 9 Jun 1995 12:42:19 +0200
From: Judicael.Courant@lip.ens-lyon.fr (Judicael Courant)
Message-Id: <9506091042.AA18436@champagne.ens-lyon.fr>
To: pn@univ-angers.fr
In-Reply-To: <199506090729.JAA03487@vink.Univ-Angers.Fr> (message from Pascal Nicolas on Fri, 9 Jun 95 9:29:41 METDST)
Subject: Re: vector dot multiply
> In order to avoid to (re)compute the length of a at each recursive call, you
> can modify a little your function as follows
>
> let dot a b = let rec dot_aux a b i sum L =
> if i < L then
> dot_aux a b (i+1) (sum +. (a.(i) *. b.(i))) L
> else
> sum
> in dot_aux a b 0 0.0 (vect_length a) ;;
in order to avoid adding a new parameter, one can also write :
let dot a b =
let rec dot_aux i sum =
match i with
-1 -> sum
| i -> dot_aux (i-1) (sum +. (a.(i) *. b.(i)))
else
sum
in dot_aux ((vect_length a)-1) 0.0 ;;
let dot a b = let rec dot_aux i sum =
if i >= 0 then
dot_aux (i-1) (sum +. (a.(i) *. b.(i))) L
else
sum
in dot_aux ((vect_length a)-1) 0.0 ;;
(notice that it is a classical way to obtain a tail-recursion from
a non-terminal one : the previous form is obtained from
let dot a b
let rec dot_aux i =
match i with
0 -> 0
| k -> (a.(i) * b.(i)) + (dot_aux (i-1))
in dot_aux ((vect_length a)-1);;
as
let fact n =
match n with
0 -> 1
| k -> k*(fact (k-1))
;;
becomes
let fact n =
let rec fact_aux n prod =
match n with
0 -> prod
| k -> k*(fact_aux (k-1))
;;
)
Judicael Courant
-- || Judicael.Courant@ens-lyon.fr \\ ``Big Brother is watching \\ || http://www.ens-lyon.fr/~jcourant/ \\ YOU ! '' \\ || tel : 72 72 85 82 \\ G. Orwell, 1984 \\