Skip to content

Instantly share code, notes, and snippets.

@ericyd
Created November 16, 2018 06:05
Show Gist options
  • Save ericyd/91c056a527aa4b53bd451ba1641aea2c to your computer and use it in GitHub Desktop.
Save ericyd/91c056a527aa4b53bd451ba1641aea2c to your computer and use it in GitHub Desktop.
Ruby Compose
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