0

I have just started using Haskell interpreter.

Can anyone tell me what's wrong with this code:(for Fibonacci)

fib :: Int -> Int
fib n
|n==0 =0
|n==1 =1
|n>1  =fib(n-2) + fib(n-1)

I am getting this error message:

 fib.hs:3:1: parse error on input `|'
 [1 of 1] Compiling Main             ( fib.hs, interpreted )
 Failed, modules loaded: none.

2 Answers 2

4

Haskell is indentation sensitive. In particular the |'s need to be indented further than the function name:

fib :: Int -> Int
fib n
  |n==0 =0
  |n==1 =1
  |n>1  =fib(n-2) + fib(n-1)

Also, it is more idiomatic to use pattern matching for comparing with a constant:

fib :: Int -> Int
fib 0 =0
fib 1 =1
fib n
  |n>1  =fib(n-2) + fib(n-1)
Sign up to request clarification or add additional context in comments.

2 Comments

Do we need the guard in the last declaration?
@ssm Not strictly, but it gives a faster error on attempts to call it with negative numbers. I really just left it in because it was in the original.
1

You have to indent the next lines at least one space, e.g.:

fib :: Int -> Int
fib n
 |n==0 =0
 |n==1 =1
 |n>1  =fib(n-2) + fib(n-1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.