Fibonacci sequence: Difference between revisions

Content deleted Content added
Line 484: Line 484:
else
else
fib_rec (n - 1) + fib_rec (n - 2)</ocaml>
fib_rec (n - 1) + fib_rec (n - 2)</ocaml>

The previous way is the naive form, because for most n the fib_rec is called twice, and it is not tail recursive because it adds the result of two function calls. The next version resolves these problems:

<ocaml>
let fib n =
let v = 0
and vn = 1 in
let rec aux i v vn =
if i >= n then v else
aux (i+1) (v+vn) v
in
aux 0 v vn
;;
</ocaml>


=={{header|Oz}}==
=={{header|Oz}}==