【问题标题】:Why does Haskell not allow pattern matching in comprehensions?为什么 Haskell 不允许在推导中进行模式匹配?
【发布时间】:2018-11-18 19:28:41
【问题描述】:

我编写了以下(微不足道的)函数:

h c = [f x | x <- a, f <- b, (a, b) <- c]

我原以为这会被取消糖分:

h c = do (a, b) <- c
         f <- b
         x <- a
         return (f x)

反过来,脱糖(忽略 fail 的东西)为:

h c = c >>= \(a, b) -> b >>= \f -> a >>= \x -> return (f x)

但是,GHCi 返回错误:

<interactive>:24:17: error: Variable not in scope: a :: [a1]
<interactive>:20:27: error:
    Variable not in scope: b :: [t0 -> b1]

这似乎很荒谬,因为ab 确实在范围内。

【问题讨论】:

    标签: list haskell scope list-comprehension monads


    【解决方案1】:

    您的绑定顺序错误。

    h c = [f x | (a,b) <- c, f <- b, x <- a]
    

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2021-12-27
      • 2012-07-05
      • 2014-10-12
      • 1970-01-01
      • 2017-11-13
      相关资源
      最近更新 更多