为什么 Haskell 不允许在理解中进行模式匹配?
Why does Haskell not allow pattern matching in comprehensions?
我编写了以下(简单的)函数:
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 returns 错误:
<interactive>:24:17: error: Variable not in scope: a :: [a1]
<interactive>:20:27: error:
Variable not in scope: b :: [t0 -> b1]
这似乎是荒谬的,因为 a
和 b
确实在范围内。
您的绑定顺序错误。
h c = [f x | (a,b) <- c, f <- b, x <- a]
我编写了以下(简单的)函数:
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 returns 错误:
<interactive>:24:17: error: Variable not in scope: a :: [a1]
<interactive>:20:27: error:
Variable not in scope: b :: [t0 -> b1]
这似乎是荒谬的,因为 a
和 b
确实在范围内。
您的绑定顺序错误。
h c = [f x | (a,b) <- c, f <- b, x <- a]