为什么Haskell不允许在理解中进行模式匹配?

sch*_*ine 3 monads haskell scope list-comprehension list

我写了以下(琐碎)函数:

h c = [f x | x <- a, f <- b, (a, b) <- c]
Run Code Online (Sandbox Code Playgroud)

我本以为这是因为:

h c = do (a, b) <- c
         f <- b
         x <- a
         return (f x)
Run Code Online (Sandbox Code Playgroud)

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

h c = c >>= \(a, b) -> b >>= \f -> a >>= \x -> return (f x)
Run Code Online (Sandbox Code Playgroud)

但是,GHCi会返回错误:

<interactive>:24:17: error: Variable not in scope: a :: [a1]
<interactive>:20:27: error:
    Variable not in scope: b :: [t0 -> b1]
Run Code Online (Sandbox Code Playgroud)

这似乎是荒谬的,因为a并且b确实在范围内.

Jor*_*ano 12

您的绑定顺序错误.

h c = [f x | (a,b) <- c, f <- b, x <- a]
Run Code Online (Sandbox Code Playgroud)