3
我有一個生成Fibonacci數的函數:OCaml中創建斐波那契數的列表
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");;
但我真正想要的是它返回說號碼列表。我嘗試這樣做:
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");;
但ocamlc
File "main.ml", line 2, characters 4-174: Error: This expression has type int list but an expression was expected of type int
(2個線字符4-174對應匹配塊)說。我想這個返回類型「int list」,爲什麼它推斷類型int?
哦,謝謝!當你指出它時,這是非常明顯的... – user1044459
@ user1044459你是如何解決它的?你能分享一下代碼片嗎? – Erhan