我有一个生成斐波那契数的函数:
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");;
Run Code Online (Sandbox Code Playgroud)
但我真正想要的是它返回所述数字的列表。我试过这个:
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");;
Run Code Online (Sandbox Code Playgroud)
但 ocamlc 说
文件“main.ml”,第 2 行,字符 4-174:错误:此表达式的类型为 int list,但表达式应为 int 类型
(第 2 行字符 4-174 对应于匹配块)。我希望它返回类型“int list”,为什么它推断类型int?