4

I have a function that generates Fibonacci numbers:

let rec fib n =
    match n with
    | (0 | 1) -> 1
    | x when x > 0 -> (fib (x-2) + fib (x-1))
    | _ -> raise (Invalid_argument "Negative value supplied to fib");;

but what I really want is for it to return a list of said numbers. I tried this:

let rec fib n list =
    match n with
    | (0 | 1) -> 1 :: []
    | x when x > 0 -> (fib (x-2) list + fib (x-1) list) :: list
    | _ -> raise (Invalid_argument "Negative value supplied to fib");;

But ocamlc says

File "main.ml", line 2, characters 4-174: Error: This expression has type int list but an expression was expected of type int

(Line 2 characters 4-174 corresponds to the match block). I want this to return type "int list", why is it inferring type int?

nlucaroni
  • 47,556
  • 6
  • 64
  • 86
user1044459
  • 57
  • 1
  • 5

2 Answers2

5

The expression fib (x - 2) list + fib (x - 1) list requires fib to return int, because (+) takes int as parameters.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
2

If anyone looking for a solution to get the list of fibonacci numbers here is my solution. This works until certain value (max fib 91).

let fib n =
  let rec aux acc n2 n1 = function
  | 1 -> acc
  | c -> aux ((n2 + n1) :: acc) n1 (n2 + n1) (c - 1)
  in
  List.rev(aux [1; 0] 0 1 (n - 1))
;;
Erhan
  • 1,126
  • 8
  • 11