Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: vector dot multiply
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Judicael.Courant@l...
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      \\