Created
April 18, 2011 20:56
-
-
Save erikpukinskis/926156 to your computer and use it in GitHub Desktop.
My attempt at Lisp CLOS-style method definitions in Ruby
This file contains 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
# By default, Ruby invokes class methods based on the number of parameters, ignoring | |
# the parameter type. I was curious if I could implement the method invocation pattern | |
# used in Lisp's CLOS, where you can have multiple methods that each accepts the same | |
# number of paraemters, but with different types. | |
# | |
# Needs Ruby 1.9 | |
class Object | |
def self.defm(sym, *classes, &block) | |
@defm_methods ||= {} | |
@defm_methods[sym] ||= {} | |
@defm_methods[sym][classes] = block | |
define_method sym do |*params| | |
self.class.defm_methods[sym].each do |classes,proc| | |
if classes == params.map(&:class) | |
params.inject(proc.curry) {|proc,param| proc[param]} | |
end | |
end | |
end | |
end | |
def self.defm_methods | |
@defm_methods | |
end | |
end | |
# Example: | |
class Onion | |
def dice | |
puts "dicing!" | |
end | |
end | |
class Bread | |
def slice | |
puts "slicing!" | |
end | |
end | |
class Chef | |
defm :prep, Onion do |onion| | |
onion.dice | |
end | |
defm :prep, Bread do |bread| | |
bread.slice | |
end | |
end | |
chef = Chef.new | |
chef.prep(Bread.new) | |
chef.prep(Onion.new) | |
# Output: | |
# | |
# slicing! | |
# dicing! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment