Ethiopian multiplication: Difference between revisions

m
m (→‎{{header|OCaml}}: broke lines too long)
m (→‎{{header|OCaml}}: indentation)
Line 1,013:
=={{header|OCaml}}==
<lang ocaml>(* We optimize a bit by not keeping the intermediate lists, and summing
the right column on-the-fly, like in the C version.
The function takes "halve" and "double" operators and "is_even" predicate as arguments,
but also "is_zero", "zero" and "add". This allows for more general uses of the
ethiopian multiplication. *)
let ethiopian is_zero is_even halve zero double add b a =
let rec g a b r = if is_zero a then r else g (halve a) (double b)
if is_zero a
(if not (is_even a) then add b r else r) in g a b zero;;
then (r)
else g (halve a) (double b) (if not (is_even a) then (add b r) else (r) in g a b zero;;)
in
g a b zero
;;
 
let imul =
let imul = ethiopian (( = ) 0) (fun x -> x mod 2 = 0) (fun x -> x / 2) 0 (( * ) 2) ( + );;
 
imul 17 34;;
Line 1,027 ⟶ 1,033:
 
(* Now, we have implemented the same algorithm as "rapid exponentiation",
merely changing operator names *)
let ipow =
ethiopian (( = ) 0) (fun x -> x mod 2 = 0) (fun x -> x / 2) 1 (fun x -> x*x) ( * )
Line 1,061 ⟶ 1,067:
 
(* Here zero is the starting value for the accumulator of the sums
of values in the right column in the original algorithm. But the "add"
me do something else, see for example the RosettaCode page on
"Exponentiation operator". *)</lang>
 
=={{header|Octave}}==