Created
May 16, 2014 09:19
-
-
Save ifyouseewendy/5191ca70001d1b66a1b8 to your computer and use it in GitHub Desktop.
a Proc#curry note from http://www.sitepoint.com/functional-programming-techniques-with-ruby-part-ii/
This file contains hidden or 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
| # http://ruby-doc.org/core-2.0/Proc.html#method-i-curry | |
| # | |
| # curry → a_proc | |
| # | |
| # Returns a curried proc. | |
| # | |
| # curry(arity) → a_proc | |
| # | |
| # If the optional arity argument is given, it determines the number of arguments. | |
| # | |
| # + If a sufficient number of arguments are supplied, it passes the supplied arguments to the original proc and returns the result. | |
| # + Otherwise(partial function application), returns another curried proc that takes the rest of arguments. | |
| # | |
| # --> version 1 | |
| def add(a, b); a+b; end | |
| def subtract(a, b); a-b; end | |
| def multiply(a, b); a*b; end | |
| def divide(a, b); a/b; end | |
| # --> version 2 | |
| def apply_math(fn, a, b) | |
| a.send(fn, b) | |
| end | |
| apply_math(:+, 1, 2) # => 3 | |
| # We have to write out that function name every time?! | |
| # --> version 3, using curring | |
| apply_math = ->(fn, a, b){ a.send(fn, b) } | |
| add = apply_math.curry.(:+) | |
| subtract = apply_math.curry.(:-) | |
| multiply = apply_math.curry.(:*) | |
| divide = apply_math.curry.(:/) | |
| add.(1, 2) # => 3 | |
| increment = add.curry.(1) | |
| increment.(41) # => 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment