Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A not Nil or Unbound thing representation
- class Unbound; end
- module PatternMatching
- def self.included(base)
- base.send(:extend, PMMethods)
- end
- module PMMethods
- attr_reader :pm_methods, :pattern
- private
- def match(*args)
- @pattern = [*args]
- end
- def who_match(m, args)
- @pm_methods.find_all do |el|
- (el[:name] == m && pattern_match(el[:pattern], args))
- end
- end
- def method_missing(m, *args)
- super if @pm_methods == nil
- return who_match(m, args)[0][:block].call(*args)
- end
- def pattern_match(pattern, args)
- return false unless pattern.size == args.size
- c = -1
- pattern.each do |p|
- c = c + 1
- return false unless single_pattern_match(p, args[c])
- end
- end
- def single_pattern_match(pattern, arg)
- case
- when (arg == pattern)
- true
- when (pattern == Unbound)
- arg != nil
- when (pattern.is_a? Regexp)
- arg =~ pattern
- when (pattern.is_a? Class)
- arg.is_a?(pattern)
- end
- end
- def fun (name, &block)
- if @pattern == nil
- raise "You need specify a pattern"
- else
- @pm_methods = [] if @pm_methods == nil
- @pm_methods << {:name=>name ,:block=>block, :pattern=>@pattern}
- @pattern = nil
- end
- end
- end
- end
Add Comment
Please, Sign In to add comment