haskell - 匿名函数的范围可见性

标签 haskell lambda scope anonymous-function

我目前正在阅读“Real World Haskell”,并对其中实现的一个函数感到困惑:

parseP5_take2 :: L.ByteString -> Maybe (Greymap, L.ByteString)
parseP5_take2 s =
    matchHeader (L8.pack "P5") s       >>?
    \s -> skipSpace ((), s)           >>?
    (getNat . snd)                    >>?
    skipSpace                         >>?
    \(width, s) ->   getNat s         >>?
    skipSpace                         >>?
    \(height, s) ->  getNat s         >>?
    \(maxGrey, s) -> getBytes 1 s     >>?
    (getBytes (width * height) . snd) >>?
    \(bitmap, s) -> Just (Greymap width height maxGrey bitmap, s)

我无法得到的是 widthheight 和其他内容如何从匿名函数作用域中泄漏并在最新表达式中变得可用。

RWH的确切位置: http://book.realworldhaskell.org/read/code-case-study-parsing-a-binary-data-format.html#id624895

正如我所料,简化的自己的代码失败了:

Prelude> (\x -> x) 5 + (\y -> x) 6

<interactive>:4:22: Not in scope: `x'

那么为什么它在他们的代码中起作用呢?

最佳答案

每个 lambda 表达式 extends as far to the right as possible .

The grammar is ambiguous regarding the extent of lambda abstractions, let expressions, and conditionals. The ambiguity is resolved by the meta-rule that each of these constructs extends as far to the right as possible.

使用 widthheight 的表达式确实在作用域内,因为它们位于引入它们的 lambda 内部。

关于haskell - 匿名函数的范围可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27466047/

相关文章:

Haskell:将非无限列表变成无限列表+惰性(euler 391)

haskell - 有谁知道(或记得)违反类(Class)法会如何导致 GHC 出现问题?

c++ - 指向 lambda 的智能指针

python - 在 lambda 中使用 __iadd__?

c++ - C++ 循环中的作用域

c++ - 如何将成员函数引入作用域?

haskell - 如何定义适合证明的类型级列表索引?

haskell - 重叠实例可以,但仍然失败

java - 方法引用中的返回类型错误 : Cannot convert Employee to Optional<U>

javascript - 返回变量值以在另一个函数中使用