首页 > 解决方案 > 如何将 Haskell 中带有匿名函数的折叠重写为常规函数?

问题描述

我正在尝试使用 Haskell 自学函数式编程。

我很难理解柯里化和 lambdas。

这是一个生成列表前缀列表的函数(输出列表列表)。

foldr (\element accumulator -> [] : map (element:) accumulator) [[]]

我正在尝试将其重写为没有 lambda 的常规函数​​,以帮助我了解 lambdas 的工作原理。我该怎么做?我被困住了。我需要一个辅助功能吗?谢谢你。

标签: haskelllambdafunctional-programmingfoldcurrying

解决方案


是的,您将需要一个辅助函数。 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

这些都是等价的。)


推荐阅读