我目前正在阅读“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)
我无法得到的是 width
、height
和其他内容如何从匿名函数作用域中泄漏并在最新表达式中变得可用。
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.
使用 width
和 height
的表达式确实在作用域内,因为它们位于引入它们的 lambda 内部。
关于haskell - 匿名函数的范围可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27466047/