RosettaCodeData/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml

20 lines
473 B
Text
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
open Num
2020-02-17 23:21:07 -08:00
let fib =
let rec fib_aux f0 f1 = function
| 0 -> f0
| 1 -> f1
| n -> fib_aux f1 (f1 +/ f0) (n - 1)
in
fib_aux (num_of_int 0) (num_of_int 1)
2015-11-18 06:14:39 +00:00
2020-02-17 23:21:07 -08:00
(* support for negatives *)
2015-11-18 06:14:39 +00:00
let fib n =
2020-02-17 23:21:07 -08:00
if n < 0 && n mod 2 = 0 then minus_num (fib (abs n))
else fib (abs n)
2017-09-23 10:01:46 +02:00
;;
2020-02-17 23:21:07 -08:00
(* It can be called from the command line with an argument *)
(* Result is send to standart output *)
let n = int_of_string Sys.argv.(1) in
print_endline (string_of_num (fib n))