对参数进行排序以利用柯里化
我最近两次重构了代码,以便更改参数的顺序,因为有太多代码,其中像 flip
或 \x -> 这样的黑客行为。 foo bar x 42 正在发生。
在设计函数签名时,哪些原则可以帮助我充分利用柯里化?
I have twice recently refactored code in order to change the order of parameters because there was too much code where hacks like flip
or \x -> foo bar x 42
were happening.
When designing a function signature what principles will help me to make the best use of currying?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于轻松支持柯里化和部分应用的语言,有一系列引人注目的论点,最初来自 Chris Okasaki:
为什么?然后,您可以很好地对数据进行操作。例如
插入1 $插入2 $插入3 $
。这也有助于状态函数。标准库,例如“容器” 遵循此约定。
有时会给出备用参数以将数据结构放在第一位,因此可以将其封闭,从而在静态结构(例如查找)上产生更简洁的函数。然而,广泛的共识似乎是这并不是一个胜利,特别是因为它迫使你使用大量括号的代码。
对于递归函数,通常将变化最大的参数(例如累加器)作为最后一个参数,而变化最小的参数(例如函数参数) )在开始时。这与最后一种数据结构风格很好地结合在一起。
中给出了冈崎视图的摘要他的爱迪生库(又一个数据结构库):
For languages that support currying and partial-application easily, there is one compelling series of arguments, originally from Chris Okasaki:
Why? You can then compose operations on the data nicely. E.g.
insert 1 $ insert 2 $ insert 3 $ s
. This also helps for functions on state.Standard libraries such as "containers" follow this convention.
Alternate arguments are sometimes given to put the data structure first, so it can be closed over, yielding functions on a static structure (e.g. lookup) that are a bit more concise. However, the broad consensus seems to be that this is less of a win, especially since it pushes you towards heavily parenthesized code.
For recursive functions, it is common to put the argument that varies the most (e.g. an accumulator) as the last argument, while the argument that varies the least (e.g. a function argument) at the start. This composes well with the data structure last style.
A summary of the Okasaki view is given in his Edison library (again, another data structure library):
首先放置您最有可能重复使用的参数。函数参数就是一个很好的例子。您更有可能想要将 f 映射到两个不同的列表,而不是想要将许多不同的函数映射到同一个列表。
Place the arguments that you are most likely to reuse first. Function arguments are a great example of this. You are much more likely to want to
map f
over two different lists, than you are to want to map many different functions over the same list.我倾向于做你所做的事情,选择一些看起来不错的订单,然后如果发现另一个订单更好则进行重构。该顺序在很大程度上取决于您将如何使用该函数(自然)。
I tend to do what you did, pick some order that seems good and then refactor if it turns out that another order is better. The order depends a lot on how you are going to use the function (naturally).