2011-11-13 46 views
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?

回答

4

表達fib (x - 2) list + fib (x - 1) list要求fib返回int,因爲(+)需要int作爲參數。

+0

哦,謝謝!當你指出它時,這是非常明顯的... – user1044459

+0

@ user1044459你是如何解決它的?你能分享一下代碼片嗎? – Erhan