Created
August 3, 2012 07:03
-
-
Save yuroyoro/3245256 to your computer and use it in GitHub Desktop.
Ruby1.8.7でcurry化
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
# Rubyでcurry化(for 1.8.7) | |
# | |
# [17] pry(main)> :to_s.curry.call("a") | |
# "a" | |
# [18] pry(main)> "foo".method(:+).curry | |
# #<Proc:0x0000000005e55358@(pry):15> | |
# [21] pry(main)> "foo".method(:+).curry.call("aa") | |
# "fooaa" | |
# [22] pry(main)> p = lambda{|a,b,c| a + b + c} | |
# #<Proc:0x0000000005ad1cb8@(pry):43> | |
# [23] pry(main)> add10 = p.curry[10] | |
# #<Proc:0x0000000005e52270@(pry):21> | |
# [24] pry(main)> add15f = add10[5] | |
# #<Proc:0x0000000005e52270@(pry):21> | |
module CurryingFunction | |
def curry | |
f = self.to_proc | |
arity = (f.arity >= 0) ? f.arity : -(f.arity + 1) | |
return f if arity == 0 | |
lambda{|arg| __curry(f, arity, arg, []) } | |
end | |
private | |
def __curry(f, arity, arg, passed) | |
args = passed + [arg] | |
return f.call(*args) if arity == 1 | |
lambda{|arg| __curry(f, arity - 1, arg, args) } | |
end | |
end | |
[Proc, Method, Symbol].each do |klass| | |
klass.send(:include, CurryingFunction) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment