So, here's how to do currying with blocks, not with methods:
def curry(&block)
arity = (block.arity >= 0) ? block.arity : -(block.arity + 1)
return block[] if arity == 0
args = []
innermost = lambda do |last,*extra|
args[arity-1] = last
block[*(args+extra)]
end
(0...(arity-1)).to_a.reverse.inject(innermost) do |inner,i|
lambda do |arg_i,*extra|
args[i] = arg_i
if extra.empty?
inner
else
inner[*extra]
end
end
end
end
And in practice, this works pretty well. The arguments can be curry or not, and additional arguments are collected, as usual:
irb> (curry { |x,y| x + y })[1,2]
#=> 3
irb> (curry { |x,y| x + y })[1][2]
#=> 3
irb> (curry { |x,*ys| ys << x })[1]
#=> [1]
irb> (curry { |x,*ys| ys << x })[1,2,3]
#=> [2, 3, 1]
irb> (curry { |x,y,*zs| zs << (x+y) })[1,2]
#=> [3]
irb> (curry { |x,y,*zs| zs << (x+y) })[1,2,4]
#=> [4, 3]
irb> (curry { |x,y,*zs| zs << (x+y) })[1][2]
#=> [3]
irb> (curry { |x,y,*zs| zs << (x+y) })[1][2,4]
#=> [4, 3]
irb> (curry { |a,b,c,d,e| a+b+c+d+e })[1,2,3,4,5]
#=> 15
irb> (curry { |a,b,c,d,e| a+b+c+d+e })[1][2][3][4][5]
#=> 15
irb> (curry { |a,b,c,d,e| a+b+c+d+e })[1,2][3][4][5]
#=> 15
irb> (curry { |a,b,c,d,e| a+b+c+d+e })[1][2,3,4][5]
#=> 15
I made a constructive decision that no-arg blocks return an immediate value for currying:
irb> curry { 3 }
#=> 3
irb> curry { |*xs| xs }
#=> []
This is necessary in order not to interrupt work []every time (and is quite similar to Haskell).