Created
November 16, 2018 06:05
-
-
Save ericyd/91c056a527aa4b53bd451ba1641aea2c to your computer and use it in GitHub Desktop.
Ruby Compose
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
add = Proc.new{|a| a + 2} | |
times = Proc.new{|a| a * 2} | |
def compose2(f, g) | |
Proc.new {|*x| f.call(g.call(*x))} | |
end | |
def compose(*x) | |
x.reduce { |all, a| compose2(all, a) } | |
end | |
add_times = compose2(add, times) | |
puts add_times.call(4) # => (4 * 2) + 2 = 10 | |
ata = compose(add, times, add, times) | |
p ata.call(4) # => (((4 * 2) + 2) * 2) + 2 = 22 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment