I've tried to make an iterative/tail-recursive version of a function to compute the nth number of the Fibonacci sequence, but I'm getting parse error (possibly incorrect indentation). Why is this happening? The code I'm using:
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
To be clear, I'm trying to understand the error - why it's happening, how it should be corrected - and not trying to implement fib efficiently (I understand the popular zipWith implementation here already, for instance).
Thanks!
The guard part has to be indented at least one character relative to the function name. The following thus works:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With