haskell - 在 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 代码是如何工作的?
解决方案
我们可以评估表达式,用它自己的定义替换每个定义的标识符。
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
推荐阅读
- javascript - 在行分组级别 ag-grid 启用对单元格字段的编辑
- java - 如何在 jar 中重新定位包以获取 gradle 依赖项
- linux - 使用远程节点 Docker 在 Linux Cloud (CentOS 8) 上部署 ASP.NET MVC core 3 应用程序
- flutter - 在颤振中创建可重用小部件的简单方法是什么?
- kubernetes - openshift 3.12 websocket ERR_CONNECTION_ABORTED
- java - 如何在 Java 中为按钮处理程序创建一个单独的类?
- docker - 普通 docker 镜像和 s2i 镜像有什么区别?
- java - 在应用中使用谷歌地图时报错:cxm: Can't load code for MapsDynamite.apk
- npm - “yarn install --frozen-lockfile”的 NPM 等价物是什么?
- hive - 自定义udf函数时如何添加maven依赖