Created
October 4, 2011 21:21
-
-
Save mikewadhera/1262846 to your computer and use it in GitHub Desktop.
Currying in ruby 1.8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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