3

我试图制作一个函数的迭代/尾递归版本来计算斐波那契数列的第n个数,但我得到parse error (possibly incorrect indentation). 为什么会这样?我正在使用的代码:

fib n
    | n < 2 = n
    | otherwise = fibhelper 0 1 2 n
    where fibhelper a b curr num
          | curr == num = a + b
          | curr < num = fibhelper b (a+b) (curr+1) num

需要明确的是,我试图理解错误——它为什么会发生,应该如何纠正——而不是试图有效地实施(例如,我已经了解了这里fib的流行zipWith实施)。

谢谢!

4

1 回答 1

8

保护部分必须相对于函数名缩进至少一个字符。因此,以下工作:

fib n
    | n < 2 = n
    | otherwise = fibhelper 0 1 2 n
    where fibhelper a b curr num
           | curr == num = a + b  -- moved one character to the left.
           | curr < num = fibhelper b (a+b) (curr+1) num
于 2010-12-15T15:52:10.727 回答