在 Haskell 中使用匿名函数

Using anonymous functions in Haskell

我正在阅读 Get Programming with Haskell 以了解函数式编程。在第 10 课中,作者讨论了使用函数式编程来创建使用闭包的简单对象。到目前为止,本书的主题包括高阶函数、lambda 函数和闭包。

他描述了以下内容:

simpleObject intAttribute= \message -> message intAttribute

simpleObject returns 一个实际上存储 intAttribute 的闭包。闭包将函数作为参数并提供 intAttribute 作为参数。例如(我的):

obj = simpleObject 5
doubleIt x = 2 * x
obj doubleIt (returns 10)

至此我想我已经很清楚了。

然后作者描述了一个类似于以下内容的访问器:

getAttribute y = y (\x -> x)
getAtrribute obj (returns 5)

代码按预期工作,返回捕获的 intAttribute。这就是我迷路的地方。 getAttribute 代码如何工作?

我们可以用自己的定义替换每个定义的标识符来评估表达式。

getAtrribute obj
= { def. getAttribute }
obj (\x -> x)
= { def. obj. }
simpleObject 5 (\x -> x)
= { def. simpleObject }
(\message -> message 5) (\x -> x)
= { beta reduction }
(\x -> x) 5
= { beta reduction }
5