如何在GHCi中使用多个where子句? [英] How do I use multiple where clauses in GHCi?

查看:79
本文介绍了如何在GHCi中使用多个where子句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次玩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| :}

它给出了以下错误:

<interactive>:1:142: parse error on input `='

有人可以指出我所缺少的方向吗?

Could someone kindly point me in the direction of what I'm missing?

推荐答案

摘自ghci帮助手册(

From the help manual of ghci (http://www.haskell.org/ghc/docs/6.10.4/html/users_guide/interactive-evaluation.html):

这种多行命令可与任何GHCi命令一起使用,并且:{:}之间的行被简单地合并为一行以进行解释.这意味着每个这样的组在合并时必须形成一个有效的命令,并且不使用布局规则.

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| :}


在最新版本的GHCi中,似乎需要一对大括号.


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

这篇关于如何在GHCi中使用多个where子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆