Skip to content

Instantly share code, notes, and snippets.

@franzejr
Created December 29, 2015 02:33
Show Gist options
  • Save franzejr/ce9a9e814ae9deb14017 to your computer and use it in GitHub Desktop.
Save franzejr/ce9a9e814ae9deb14017 to your computer and use it in GitHub Desktop.
Higher Order Functions in Ruby
# 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