【问题标题】:How do I use multiple where clauses in GHCi?如何在 GHCi 中使用多个 where 子句?
【发布时间】:2010-06-18 07:35:46
【问题描述】:

我是第一次使用 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 `='

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

【问题讨论】:

    标签: haskell ghci


    【解决方案1】:

    来自ghci的帮助手册(http://www.haskell.org/ghc/docs/6.10.4/html/users_guide/interactive-evaluation.html):

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

    因此你必须在每个定义之间插入一个分号,例如

    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
    

    【讨论】:

    • 漂亮,很好的答案。以前从未见过或使用过这个。
    • 从 GHC 7.6.3 开始在 Ubuntu 软件包中不起作用:输入“where”时出现解析错误
    • @kennytm 您可以引用任何文档吗?我无法理解这些奇怪的规则。为什么我需要花括号?
    • @constantius:我不知道为什么,只是一些尝试和错误。
    • 因为这样的时刻我讨厌 Haskell :(
    【解决方案2】:

    The golden rule of indentation: 作为某个表达式一部分的代码应该比该表达式的开头更缩进(即使该表达式不是该行的最左侧元素)。

    Prelude> :set +m
    

    错误:

    Prelude> let foo = x
    Prelude|     where x = 1
    Prelude| 
    
    <interactive>:3:1:
        parse error in let binding: missing required 'in'
    

    右:

    Prelude> let foo = x
    Prelude|      where x = 1
    Prelude| 
    

    不需要大括号或分号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多