Created
August 30, 2014 07:39
-
-
Save mocoso/aa9b8d85e6d5ac48dd6c to your computer and use it in GitHub Desktop.
A pure Ruby implementation of curry for Proc objects
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
# A pure Ruby implementation of curry for Proc objects. | |
# | |
# For example | |
# | |
# >> f = Proc.new { |x, y| x**y } | |
# => #<Proc:0x007fb662016c18@(eval):1> | |
# >> curry(f).call(5).call(3) | |
# => 125 | |
# | |
def curry(p) | |
eval( | |
(1..p.arity). | |
to_a. | |
reverse. | |
inject("p.call(#{(1..p.arity).map { |n| "x#{n}" }.join(', ')})") do |result, n| | |
"Proc.new { |x#{n}| #{result} }" | |
end | |
) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment