Created
June 27, 2014 21:05
-
-
Save qxjit/08038faf810c0f5857e7 to your computer and use it in GitHub Desktop.
Ruby proc & symbol composition
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
def comp(*gs) | |
id = -> x { x } | |
gs.inject(id) do |f,g| | |
-> x do | |
f.to_proc.call g.to_proc.call x | |
end | |
end | |
end | |
times_2 = -> x { x * 2 } | |
plus_3 = -> x { x + 3 } | |
puts comp(times_2, plus_3).call(1) #=> 8 | |
puts comp(plus_3, times_2).call(1) #=> 5 | |
p (9..12).map(&comp(:reverse, :to_s)) #=> ["9", "01", "11", "21"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment