Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse error in simple Haskell Fibonacci implementation

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!

like image 281
Kiwi Avatar asked May 04 '26 09:05

Kiwi


1 Answers

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
like image 112
nominolo Avatar answered May 05 '26 21:05

nominolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!