I just downloaded the full Haskell platform and put in some code from my teacher to try and break, but it turns out it (or something) was already broken because when I evaluate the main
expression I get a parsing error.
data Shape = Circle Double | Rect Double Double
area :: Shape -> Double
area (Circle radius) = 3.1415 * radius * radius
area (Rect width height) = width * height
Error
<interactive>:17:56: error: parse error on input ‘::’
Is there something wrong with my installation? I'm running version 8.2.2
EDIT: Here is a verbatim copypaste of the error directly from the WinGHCi window
GHCi, version 8.2.2: http://www.haskell.org/ghc/ :? for help
Prelude> data Shape = Circle Double | Rect Double Double
area :: Shape -> Double
area (Circle radius) = 3.1415 * radius * radius
area (Rect width height) = width * height
<interactive>:7:54: error: parse error on input ‘::’
GHCi is a Read Eval Print Loop (REPL), so it evaluates each line as it's input. area
, on the other hand, is a multi-line expression, so if you try to input it line by line, it's going to fail as being incomplete.
You can enter multiline expressions in GHCi, though. What you need to do is enter into 'multiline mode', enter your lines, and exist the multiline mode again. You start this editing mode with :{
and close it again with :}
. Here's a full example:
Prelude> data Shape = Circle Double | Rect Double Double
Prelude> :{
Prelude| area :: Shape -> Double
Prelude| area (Circle radius) = 3.1415 * radius * radius
Prelude| area (Rect width height) = width * height
Prelude| :}
Prelude> area $ Circle 1.1
3.8012150000000005
Prelude> area $ Rect 1.2 3.4
4.08
As you can see, the definition of Shape
is already a single line, so I didn't feel the need to enter into multi-line mode at that stage. When entering the definition of area
, though, it's necessary to use :{
and :}
.
In general, however, GHCi is for experimentation and rapid feedback. You're supposed to write Haskell source code in .hs
files, often using either Stack or Cabal as a project system.