我正在学习f#而且我有一个非常微不足道的问题似乎没有意义。我正在研究Project Euler问题2,我得到了这个:
let fib (x : BigInteger) (y : BigInteger) (max : BigInteger) =
let added = x + y
if added > max then y
else fib y (x + y) max
我在递归的fib调用中遇到错误:
未定义值或构造函数'fib'
我不确定为什么。有什么帮助吗?
答案 0 :(得分:13)
因为fib
是递归函数,所以它必须以let rec
开头。
答案 1 :(得分:7)
在F#中,如果要编写递归函数,则必须使用the rec
keyword:
let rec fib (x : BigInteger) (y : BigInteger) (max : BigInteger) =
let added = x + y
if added > max then y
else fib y (x + y) max
这是因为在正常情况下,在F#中,您只能使用在当前代码之前声明的标识符,这与C#不同。
答案 2 :(得分:3)
谈到Project Euler Problem 2,您可以考虑使用Seq.unfold
进行递归而不是递归,这非常惯用并且一次性为您提供所有斐波那契数字:
let fibs = Seq.unfold (fun (current, next) ->
Some(current, (next, current + next))) (1,2)
现在fibs
代表斐波纳契数的懒惰序列:
>fibs;;
val it : seq<int> = seq[1; 2; 3; 5; ...]
要使BigInteger
只用(1,2)
代替(1I,2I)
,尽管解决方案允许您保持在普通整数范围内。