Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

haskell - How do I use multiple where clauses in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...