Last active
December 11, 2017 13:30
-
-
Save tiagopog/810c50a4bf3f3ba031a8c032de0b7de3 to your computer and use it in GitHub Desktop.
Ruby - Curry examples
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
## | |
# Simple closure | |
## | |
power = -> (x, n) { x**n }.curry #=> #<Proc:0x00556a913f6af0 (lambda)> | |
power_of_two = power.(2) #=> #<Proc:0x00556a913f2d38 (lambda)> | |
power_of_two.(10) #=> 1024 | |
power_of_ten = power.(10) #=> #<Proc:0x00556a913e03b8 (lambda)> | |
power_of_ten.(3) #=> 1000 | |
## | |
# Closure with more granular compositions | |
## | |
f = -> (a, b, c) { a + b + c }.curry | |
# Combine "a" with multiple "b" and "c"s: | |
f_a = f.(1) | |
f_a.(2, 3) #=> 6 | |
f_a.(3, 9) #=> 13 | |
# Combine "a" and "b" with multiple "c"s: | |
f_a_b = f.(1).(2) #=> 6 | |
f_a_b.(7) #=> 10 | |
## | |
# Pipe example: | |
## | |
foo = -> a, b, c { | |
c.(b.(a)) | |
}.curry | |
foo.("foo") | |
.(-> (str) { str.upcase }) | |
.(-> (str) { str << "bar"}) #=> "FOObar" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment