在Haskell中乱序处理 [英] Currying out of order in Haskell

查看:71
本文介绍了在Haskell中乱序处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Haskell中是否有一种优雅的表示法来使函数的参数乱序处理?

Is there an elegant notation for Currying the arguments of a function out of order in Haskell?

例如,如果您希望将2除以列表的所有元素,则可以编写

For example, if you wish to divide 2 by all elements of a list, you can write

map ((/) 2) [1,2,3,4,5]

但是,划分列表的所有元素似乎需要定义一个匿名函数

However to divide all elements of a list it seems you need to define an anonymous function

map (\x -> x/2) [1,2,3,4,5]

在更复杂的情况下,匿名功能很快变得笨拙.我知道在这种情况下map((*)0.5)[1,2,3,4,5]可以很好地工作,但是我想知道Haskell是否具有更优雅的方法来引用函数的参数乱了?

Anonymous functions quickly become unwieldy in more complex cases. I'm aware that in this case map ((*) 0.5) [1,2,3,4,5] would work fine, but I'm interested to know if Haskell has a more elegant way of currying arguments of a function out of order?

推荐答案

在这种情况下:

Prelude> map (/2) [1..5]
[0.5,1.0,1.5,2.0,2.5]

不仅可以将infix运算符用作普通的前缀函数,还可以以infix形式部分应用它.同样,第一个示例最好写为map (2/) [1..5]

Not only you can use an infix operator as ordinary prefix function, you can also partially apply it in infix form. Likewise, the first example would better be written as map (2/) [1..5]

此外,还有flip并不那么优雅,但它仍然是普通函数的最佳选择(当您不想通过反引号将它们转换为infix时):

Also, there's flip which is not quite as elegant, but still the best option available for ordinary functions (when you don't want to turn them into infix via backticks):

Prelude> let div' = (/)
Prelude> div' 2 1
2.0
Prelude> flip div' 2 1
0.5

这篇关于在Haskell中乱序处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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