我试图制作一个迭代/尾递归版本的函数来计算第n个Fibonacci序列,但我得到了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
Run Code Online (Sandbox Code Playgroud)
需要明确的是,我试图理解的错误-为什么它的发生,应该如何进行纠正-而不是试图实现fib有效的(我的理解流行的zipWith执行在这里已经,例如).
谢谢!
防护部件必须相对于函数名称缩进至少一个字符.因此以下工作:
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
Run Code Online (Sandbox Code Playgroud)