首页 > 解决方案 > 在 Haskell 中使用匿名函数

问题描述

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

他描述了以下内容:

simpleObject intAttribute= \message -> message intAttribute

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

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

我想我很清楚这一点。

然后作者描述了一个类似的访问器:

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

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

标签: haskellclosuresanonymous-function

解决方案


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

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

推荐阅读