订购参数使用currying [英] Ordering of parameters to make use of currying

查看:118
本文介绍了订购参数使用currying的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两次最近重构的代码,以便更改参数的顺序,因为有太多的代码,像 flip \x - > foo bar x 42 正在发生。



在设计功能签名时,什么原则可以帮助我充分利用咖喱?

解决方案

对于支持currying和部分应用程序的语言,有一个引人注目的一系列参数,最初来自Chris Okasaki: / p>


  • 将数据结构作为最后一个参数



为什么?然后,您可以很好地对数据进行操作。例如。 insert 1 $ insert 2 $ insert 3 $ s 。这也有助于状态的功能



标准库,如containers遵循这个约定



有时会给替代参数放置数据结构,所以它可以关闭,在一个更简洁的静态结构(例如查找)上产生功能。然而,广泛的共识似乎是这不是一个胜利,特别是因为它推动你的大括号代码。




  • 将最多变化的参数最后一个



对于递归函数,通常将参数最多(例如累加器)作为最后一个参数,而在开始时变化最小的参数(例如函数参数)。这个数据结构最后一个样式。






Okasaki视图的摘要在他的爱迪生图书馆(又一个数据结构库):




  • 部分应用程序:更有可能是静态的参数通常出现在其他参数之前,以便于部分应用程序。

  • 集合出现在最后:在所有情况下,操作查询单个集合或修改现有集合时,集合参数将最后显示。这是Haskell数据结构库的一个事实上的标准,并且对API有一定程度的一致性。

  • 最常见的顺序:操作代表一个井在多个数据结构上的已知数学函数,选择参数以匹配函数最常用的参数顺序。


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?

解决方案

For languages that support currying and partial-application easily, there is one compelling series of arguments, originally from Chris Okasaki:

  • Put the data structure as the last argument

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.

  • Put the most varying argument last

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):

  • 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.

这篇关于订购参数使用currying的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆