Created
December 29, 2015 02:33
-
-
Save franzejr/ce9a9e814ae9deb14017 to your computer and use it in GitHub Desktop.
Higher Order Functions in Ruby
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
# takes one or more functions as arguments | |
sum_of_powers = ->(a, b, power_function){ | |
power_function.(a) + power_function.(b) | |
} | |
power_of_2 = ->(x){ x * x } | |
puts sum_of_powers.(3 , 2, power_of_2) | |
power_of_3 = ->(x){ x * x * x} | |
puts sum_of_powers.(3 , 2, power_of_3) | |
# returns function as its results: | |
generate_sum_of_powers_of_n = ->(exponent){ | |
->(a,b){a ** exponent + b ** exponent} | |
} | |
sum_of_powers_of_2 = generate_sum_of_powers_of_n.(2) | |
sum_of_powers_of_3 = generate_sum_of_powers_of_n.(3) | |
puts sum_of_powers_of_2.(3, 2) #=> 14 | |
puts sum_of_powers_of_3.(3, 2) #=> 35 | |
# Examples were extracted from: http://leikind.org/lazy/#6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment