I'm playing around with GHCi for the first time, and I'm having some trouble writing multi-line functions. My code is as follows:
Prelude> :{
Prelude| let diffSquares lst = abs $ squareOfSums lst - sumOfSquares lst
Prelude| where
Prelude| squareOfSums lst = (fst (sumsAndSquares lst))^2
Prelude| sumOfSquares lst = snd (sumsAndSquares lst)
Prelude| sumsAndSquares = foldl (\(sms,sqrs) x -> (sms+x,sqrs+x^2)) (0,0)
Prelude| :}
It gives the following error:
<interactive>:1:142: parse error on input `='
Could someone kindly point me in the direction of what I'm missing?
If you started GHCi from the “Start” menu in Windows, then the current directory is probably something like C:\Documents and Settings\user name . Typically GHCi will show only the number of modules that it loaded after a :load command. With this flag, GHC will also list the loaded modules' names.
Introduction. GHCi is GHC's interactive environment, in which Haskell expressions can be interactively evaluated and programs can be interpreted.
Quits GHCi. You can also quit by typing control-D at the prompt. Attempts to reload the current target set (see :load ) if any of the modules in the set, or any dependent module, has changed.
From the help manual of ghci (http://www.haskell.org/ghc/docs/6.10.4/html/users_guide/interactive-evaluation.html):
Such multiline commands can be used with any GHCi command, and the lines between
:{
and:}
are simply merged into a single line for interpretation. That implies that each such group must form a single valid command when merged, and that no layout rule is used.
Therefore you must insert a semicolon between each definition, e.g.
Prelude> :{
Prelude| let a x = g
Prelude| where
Prelude| g = p x x; {- # <----- # -}
Prelude| p a b = a + b
Prelude| :}
Edit: It seems you need a pair of braces instead in the recent version of GHCi.
Prelude> :{
Prelude| let { a x = g
Prelude| where
Prelude| g = p x x
Prelude| p a b = a + b
Prelude| }
Prelude| :}
Prelude> a 5
10
The golden rule of indentation: code which is part of some expression should be indented further in than the beginning of that expression (even if the expression is not the leftmost element of the line).
Prelude> :set +m
Wrong:
Prelude> let foo = x
Prelude| where x = 1
Prelude|
<interactive>:3:1:
parse error in let binding: missing required 'in'
Right:
Prelude> let foo = x
Prelude| where x = 1
Prelude|
No need for braces or semicolons.
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