Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Currying in Ruby

Tags:

ruby

currying

I'm trying to do some currying in ruby:

def add(a,b)
  return a+b
end

plus = lambda {add}
curry_plus = plus.curry
plus_two = curry_plus[2] #Line 24
puts plus_two[3]

I get the error

func_test.rb:24:in `[]': wrong number of arguments (1 for 0) (ArgumentError)

from func_test.rb:24:in `'

But if I do

plus = lambda {|a,b| a+ b}

It seems to work. But by printing plus after the assigning with lambda both ways return the same type of object. What have I misunderstood?

like image 992
MattyW Avatar asked Nov 24 '10 22:11

MattyW


1 Answers

You're on the right track:

add = ->(a, b) { a + b }
plus_two = add.curry[2]
plus_two[4]
#> 6
plus_two[5]
#> 7

As others have pointed out, the plus lambda you defined doesn't take any arguments and calls the add method with no arguments.

like image 152
Greggory Rothmeier Avatar answered Oct 21 '22 07:10

Greggory Rothmeier