haskell - 如何在 GHCi 中使用多个 where 子句?

标签 haskell ghci

我第一次玩 GHCi,我在编写多行函数时遇到了一些麻烦。
我的代码如下:

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 `='

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

最佳答案

来自 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.



因此,您必须在每个定义之间插入分号,例如
Prelude> :{
Prelude| let a x = g
Prelude|   where
Prelude|     g = p x x;      {- # <----- # -}
Prelude|     p a b = a + b
Prelude| :}

编辑:在最新版本的 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

关于haskell - 如何在 GHCi 中使用多个 where 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3067885/

相关文章:

haskell - monad 运算符名称的继承

eclipse - 如何为 Eclipse 安装和配置 EclipseFP Haskell 插件?

haskell - 是否有 F# 工具/库将值可视化为图形(如 Haskell 的 vacuum)?

haskell - 它在从文件加载时有效,但在输入 ghci 时无效。为什么?

haskell - 不在范围内 : <*>

Haskell:定义严格的数据

haskell - 带尾递归的矩阵转置永远运行

haskell - 我有同一个 haskell/cabal 软件包的多个安装版本。哪一款投入使用?

haskell - 如何将命令行参数传递给 GHCi

Haskell 类型运算符优先级