Skip to content

Instantly share code, notes, and snippets.

@mudge
Last active August 29, 2015 14:22
Show Gist options
  • Save mudge/777442d5a604d7740740 to your computer and use it in GitHub Desktop.
Save mudge/777442d5a604d7740740 to your computer and use it in GitHub Desktop.
Composing Procs to explore ideas in Transproc (http://solnic.github.io/transproc/)
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