Partial application in haskell with multiple arguments
Given some function f(x1,x2,x3,..,xN) it is often useful to apply it partially in several places. For example, for N=3 we could define g(x)=f(1,x,3). However, the standard partial application in Haskell does not work this way and only allows us to partially apply a function by fixing its first arguments (because all functions actually only take one argument). Is there any simple way to do something like this:
g = f _ 2 _
g 1 3
with output the value of f 1 2 3
? Of course we could do a lambda-function
g=(x1 x3 -> f x1 2 x3)
but I find this quite unreadable. For example, in Mathematica it works like this, which I find quite nice:
g=f[#1,2,#2]&
g[1,3]
with output f[1,2,3]
.
Edit: Maybe I should say somehting more about the motivation. I would like to use such partially applied functions in point-style compositions, ie, in expressions like this:
h = g. f _ 2 . k
to get h 3 = g(f(k(3),2))
.
你可以阅读这个关于如何改变参数顺序的问题,然后使用部分应用程序,但是目前在Haskell中最干净和最清晰的方法就是直接:
g x y = f x 2 y
No, the simplest way is to define a lambda. You can probably try and play with flip
, but I doubt it would be cleaner and simpler than a lambda. Especially for longer list of arguments.
The simplest (and canonical) way is to define a lambda. It is much more readable if you use meaningful argument names where possible
getCurrencyData :: Date -> Date -> Currency -> IO CurrencyData
getCurrencyData fromDate toDate ccy = {- implementation goes here -}
you can define your new function with lambda syntax
getGBPData = from to -> getCurrencyData from to GBP
or without it
getGBPData from to = getCurrencyData from to GBP
or you can use combinators, but I think this is quite ugly
getGBPData = from to -> getCurrencyData from to GBP
= from to -> flip (getCurrencyData from) GBP to
= from -> flip (getCurrencyData from) GBP
= from -> (flip . getCurrencyData) from GBP
= from -> flip (flip . getCurrencyData) GBP from
= flip (flip . getCurrencyData) GBP
链接地址: http://www.djcxy.com/p/43030.html
上一篇: 用关联二元运算链接元素
下一篇: 在具有多个参数的haskell中部分应用