Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top