Skip to content

Instantly share code, notes, and snippets.

@mikewadhera
Created October 4, 2011 21:21
Show Gist options
  • Save mikewadhera/1262846 to your computer and use it in GitHub Desktop.
Save mikewadhera/1262846 to your computer and use it in GitHub Desktop.
Currying in ruby 1.8
class Proc
def curry(*args)
if args.size < self.arity
args_string = ('a'..'z').take(self.arity-args.size).join(',')
given_args = []
args.size.times {|i| given_args << "args[#{i}]"}
given_args = given_args.join(", ")
eval "lambda {|#{args_string}| self.call(#{given_args}, #{args_string})}"
elsif args.size > self.arity
raise ArgumentError, "Wrong # of arguments to curried function(#{args.size} for #{self.arity.size})"
else
self.call(*args)
end
end
alias_method :apply, :curry
end
plus = lambda {|x,y| x + y }
plus1 = plus.apply(1)
minus1 = plus.apply(-1)
plus1.apply(2) #=> 3
minus1.apply(2) #=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment