In GHCi 7.x or below, you need a let
to define things in it.
Prelude> let f x = x * 2
Prelude> f 4
8
Starting from GHC 8.0.1, top-level bindings are supported in GHCi, so OP's code will work without change.
GHCi, version 8.0.1.20161213: http://www.haskell.org/ghc/ :? for help
Prelude> f x = x * 2
Prelude> f 4
8
When you type into a Haskell source file,
f x = 2 * x
is correct.
When you type directly into ghci, you need to type let
at the start of the line:
let f x = 2 * x
A good rule of thumb for using ghci is that any code you enter should conform to do-block semantics; that is, you could assume syntactically that you're programming within the IO monad (if this is new terminology, don't worry! I'd highly recommend reading through this tutorial).
This answer illustrates this point with an example, and may provide more working insight into the nature of IO and ghci.
Starting in GHC 8.0.1 this would no longer generate an error.
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