Last active
August 29, 2015 14:22
-
-
Save mudge/777442d5a604d7740740 to your computer and use it in GitHub Desktop.
Composing Procs to explore ideas in Transproc (http://solnic.github.io/transproc/)
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
class Proc | |
def compose(g) | |
proc { |*args, &blk| call(g.call(*args, &blk)) } | |
end | |
end | |
symbolize = ->(x) { x.to_sym } | |
upcase = ->(x) { x.upcase } | |
symbolize_and_upcase = symbolize.compose(upcase) | |
%w(alice bob carol).map(&symbolize_and_upcase) | |
#=> [:ALICE, :BOB, :CAROL] | |
# Or, without monkey-patching: | |
require 'delegate' | |
class Superproc < SimpleDelegator | |
def compose(g) | |
proc { |*args, &blk| call(g.call(*args, &blk)) } | |
end | |
end | |
symbolize = Superproc.new(proc { |x| x.to_sym }) | |
upcase = Superproc.new(proc { |x| x.upcase }) | |
symbolize_and_upcase = symbolize.compose(upcase) | |
%w(alice bob carol).map(&symbolize_and_upcase) | |
#=> [:ALICE, :BOB, :CAROL] | |
# We could also steal `complement` from Clojure... | |
class Proc | |
def ! | |
proc { |*args, &blk| !call(*args, &blk) } | |
end | |
end | |
even = ->(x) { x.even? } | |
odd = !even | |
(1..10).select(&odd) | |
#=> [1, 3, 5, 7, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment