Ruby Reverse Currying: Is this possible?

六眼飞鱼酱① 提交于 2019-12-07 06:07:21

问题


Concerning currying in Ruby 1.9.x, I've been using it in some places, and can be translated like basically supporting default parameters to the proc arguments:

p = proc {|x, y, z|x + y + z}
p.curry[1] #=> returns a lambda
p.curry[1, 2] #=> returns a lambda
p.curry[1, 2, 3] #=> 6
p2 = p.curry[1, 2]
p2.(2) #=> 5
p2.(4) #=> 7

very handy, right? thing is, I would like to be able to curry in reverse, that means, fill the last argument of my proc with a random value. Like this:

p = proc{|x, y| x - y }.curry[1]
p.(4)

my desired result would be 3. this returns -3.


回答1:


i think there's no direct way of doing that and what you're doing is a bit dodgy, there probably is better solution to your problem than back-currying

what you could do to achieve desired result is wrap more procs around your procs:

p = proc{|x, y| x - y}
q = proc{|y, x| p[x, y]}
q.curry[1].(4)

in fact you can reorder arguments any way you want but believe me it gets messy very quickly



来源:https://stackoverflow.com/questions/13233875/ruby-reverse-currying-is-this-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!