Skip to content

Instantly share code, notes, and snippets.

@yuroyoro
Created August 3, 2012 07:03
Show Gist options
  • Save yuroyoro/3245256 to your computer and use it in GitHub Desktop.
Save yuroyoro/3245256 to your computer and use it in GitHub Desktop.
Ruby1.8.7でcurry化
# 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