1

I am trying to declare a function in Haskell GHCi as

fact :: Int -> Int

But I am getting this error - error: parse error on input `->'

I do not understand why this is happening. Can anyone please explain it to me? Thanks.

2
  • I get "error: Variable not in scope: fact :: Int -> Int" (AFAIK, you can't "forward-declare" a type in ghci). Which version are you using, and is that all your input?
    – molbdnilo
    Commented Nov 8, 2019 at 10:07
  • @Megha That would work with the compiler, but with GHCi the syntax has to be subtly different. This however works with GHCi v8.2.2: let { fact :: Int -> Int ; fact 0 = 1 ; fact n = n * fact (n-1) }
    – jpmarinier
    Commented Nov 8, 2019 at 10:13

1 Answer 1

5

First off, it looks like you're using a pretty old version of GHC. In newer versions, the GHCi syntax has been relaxed a bit.

But still: what you type in GHCi does not have the same rules as what you write in a Haskell source file. Specifically, the GHCi prompt is essentially an IO monad chain evaluator, the reason being that you can write stuff like

Prelude> putStrLn "Hello"
Hello

or

Prelude> readFile "test.txt" 
"fubar\nbaz"

and actually have it execute right there. By contrast, in a Haskell source file, you only declare bindings, and these can then be invoked in the main action or a GHCi session.

But in this case, you want to declare a binding within GHCi itself. You can do that too, but it's a bit awkward, basically you need to start with let and then squeeze everything in a single line:

Prelude> let fact :: Int -> Int; fact n = product [1..n]

Actually, newer GHCi version allow you to omit the let, and you can have multiple-line definitions by using a special bracket syntax:

Prelude> :{
Prelude| fact :: Int -> Int
Prelude| fact n = product [1..n]
Prelude| :}

but I would recommend against this. If you actually have some bigger definitions, better put them in a proper Haskell source and load that into GHCi.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.