Created
September 1, 2020 16:45
-
-
Save kjlape/2a687e095628ef51927eef2b9734a928 to your computer and use it in GitHub Desktop.
Playing with functional composition in ruby.
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
if Gem::Version.new("2.6") <= Gem::Version.new(RUBY_VERSION) | |
def compose(*funcs) | |
funcs.map(&:to_proc).reduce(:<<) | |
end | |
else | |
def compose(*funcs) | |
funcs.map(&:to_proc).reduce { |f, g| ->(*x) { f.call(g.call(*x)) } } | |
end | |
end | |
def a(x) | |
"a(#{x})" | |
end | |
def b(x) | |
"b(#{x})" | |
end | |
def c(x) | |
"c(#{x})" | |
end | |
results = %w[functional programming].map(&compose(method(:a), method(:b), method(:c))) | |
expected = ["a(b(c(functional)))", "a(b(c(programming)))"] | |
raise "unexpected results! 😵\nactual: #{results}\nexpected: #{expected}" unless results == expected | |
puts "✅ #{results}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment