Skip to content

Instantly share code, notes, and snippets.

@hzamani
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hzamani/c446bea100e0c55b6972 to your computer and use it in GitHub Desktop.
Save hzamani/c446bea100e0c55b6972 to your computer and use it in GitHub Desktop.
Try to have higher order messages (HOM) in ruby :-)
module Messaging
def method_missing(name, *args, &block)
each do |item|
item.send(name, *args, &block)
end
end
def compose(op)
case op
when Symbol
each(&op)
when Proc
each { |x| op.(x) }
else
raise TypeError
end
end
def call(op)
compose(op)
end
def [](other)
compose(other)
end
def |(other)
compose(other)
end
def **(other)
compose(other)
end
end
module Curring
def |(arg)
curry.call(arg)
end
def **(arg)
curry.call(arg)
end
end
Enumerator.include Messaging
Proc.include Curring
# Now we can do:
(1..10).select.odd?
# which with no hack was:
(1..10).select(&:odd?)
divisible_by = ->(m,n) { n % m == 0 }
(1..10).select ** divisible_by ** 3
# was
(1..10).select { |n| divisible_by(3,n) }
# or this :P
(1..10).select { |n| n % 3 == 0 }
@hzamani
Copy link
Author

hzamani commented Oct 11, 2014

** used because it has right to left associativity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment