使用柯里化的参数排序 [英] Ordering of parameters to make use of currying
问题描述
我最近两次重构了代码以更改参数的顺序,因为有太多的代码像 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?
推荐答案
对于容易支持柯里化和部分应用的语言,有一系列引人注目的论据,最初来自 Chris Okasaki:
For languages that support currying and partial-application easily, there is one compelling series of arguments, originally from Chris Okasaki:
- 将数据结构作为最后一个参数
为什么?然后,您可以很好地对数据进行组合操作.例如.insert 1 $ insert 2 $ insert 3 $ s
.这也有助于状态函数.
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.
标准库,例如容器"遵循这个约定.
有时会给出替代参数以将数据结构放在首位,因此可以将其关闭,从而在静态结构(例如查找)上生成更简洁的函数.然而,广泛的共识似乎是这不是一个胜利,特别是因为它促使您使用大量括号的代码.
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.
Okasaki 观点的总结在 他的 Edison 库(同样是另一个数据结构库):
A summary of the Okasaki view is given in his Edison library (again, another data structure library):
- 部分应用:更可能是静态的参数通常出现在其他参数之前,以便于部分应用.
- 集合最后出现:在查询单个集合或修改现有集合的所有情况下,集合参数将最后出现.这是 Haskell 数据结构库的事实上的标准,并为 API 提供了一定程度的一致性.
- 最常用的顺序:如果一个操作代表一个以上数据结构上的众所周知的数学函数,则选择参数以匹配该函数最常用的参数顺序.
- Partial application: arguments more likely to be static usually appear before other arguments in order to facilitate partial application.
- Collection appears last: in all cases where an operation queries a single collection or modifies an existing collection, the collection argument will appear last. This is something of a de facto standard for Haskell datastructure libraries and lends a degree of consistency to the API.
- Most usual order: where an operation represents a well-known mathematical function on more than one datastructure, the arguments are chosen to match the most usual argument order for the function.
这篇关于使用柯里化的参数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!