haskell - 如何将 Haskell 中带有匿名函数的折叠重写为常规函数?
问题描述
我正在尝试使用 Haskell 自学函数式编程。
我很难理解柯里化和 lambdas。
这是一个生成列表前缀列表的函数(输出列表列表)。
foldr (\element accumulator -> [] : map (element:) accumulator) [[]]
我正在尝试将其重写为没有 lambda 的常规函数,以帮助我了解 lambdas 的工作原理。我该怎么做?我被困住了。我需要一个辅助功能吗?谢谢你。
解决方案
是的,您将需要一个辅助函数。 where
子句是放置这样的助手的好地方。 where
子句附加到定义中,所以我需要为你的函数命名(我已经命名了它inits
)。首先将表达式逐字移出。
inits :: [a] -> [[a]]
inits = foldr helper [[]]
where
helper = \element accumulator -> [] : map (element:) accumulator
然后你可以将右边的 lambda 参数移动到左边的参数绑定,这意味着同样的事情:
inits :: [a] -> [[a]]
inits = foldr helper [[]]
where
helper element accumulator = [] : map (element:) accumulator
(你也可以只做一个参数:
helper element = \accumulator -> [] : map (element:) accumulator
这些都是等价的。)
推荐阅读
- php - wordpress php author meta data condition
- scala - Scala 奇怪的类/对象初始化
- c# - convert json to c# object. and name contains space or numbers only
- c++ - How to include zeromq header for C++ on Fedora?
- awk - finding pattern and then finding second pattern in lines before
- python - 如何在 Pyparsing 中进行适当的递归?
- spring - 不从它的超类中覆盖方法吗?
- javascript - 条件语句:不确定为什么会得到未定义的结果(JavaScipt)
- css - Vuetify - 打开相对于元素位置的对话框(例如按钮)
- java - 在回收站视图中单击 +/- 按钮时,处理学生出勤管理器的应用程序会崩溃