Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use multiple where clauses in GHCi?

Tags:

haskell

ghci

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?

like image 621
T.R. Avatar asked Jun 18 '10 07:06

T.R.


People also ask

Where is GHCi?

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.

What does GHCi mean in Haskell?

Introduction. GHCi is GHC's interactive environment, in which Haskell expressions can be interactively evaluated and programs can be interpreted.

How do I leave Haskell GHCi?

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.


2 Answers

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
like image 136
kennytm Avatar answered Oct 06 '22 21:10

kennytm


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.

like image 23
thomie Avatar answered Oct 06 '22 21:10

thomie