R – how to implement curry(partial function) in ruby

curryingruby

I need some examples of implementing curry function in ruby(1.8.6 or 1.8.7 not 1.9).

Best Answer

So here's how to do currying with blocks, rather than methods:

def curry(&block) 
  arity = (block.arity >= 0) ? block.arity : -(block.arity + 1)
  # return an immediate value if the block has one
  return block[] if arity == 0

  # otherwise, curry it argument by argument
  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
      # pass extra arguments on to inner calls
      if extra.empty?
        inner
      else
        inner[*extra]
      end
    end
  end
end

And it works fairly well in practice. Arguments can be curried or not, and extra 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 the design decision to have no-arg blocks return an immediate value on currying:

irb> curry { 3 }
#=> 3
irb> curry { |*xs| xs }
#=> []

This is necessary to avoid having to end currying with a [] every time (and is fairly Haskell-like).