Guest User

Untitled

a guest
Feb 20th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. # A not Nil or Unbound thing representation
  2. class Unbound; end
  3.  
  4. module PatternMatching
  5. def self.included(base)
  6. base.send(:extend, PMMethods)
  7. end
  8.  
  9. module PMMethods
  10. attr_reader :pm_methods, :pattern
  11.  
  12. private
  13. def match(*args)
  14. @pattern = [*args]
  15. end
  16.  
  17. def who_match(m, args)
  18. @pm_methods.find_all do |el|
  19. (el[:name] == m && pattern_match(el[:pattern], args))
  20. end
  21. end
  22.  
  23. def method_missing(m, *args)
  24. super if @pm_methods == nil
  25. return who_match(m, args)[0][:block].call(*args)
  26. end
  27.  
  28. def pattern_match(pattern, args)
  29. return false unless pattern.size == args.size
  30. c = -1
  31. pattern.each do |p|
  32. c = c + 1
  33. return false unless single_pattern_match(p, args[c])
  34. end
  35. end
  36.  
  37. def single_pattern_match(pattern, arg)
  38. case
  39. when (arg == pattern)
  40. true
  41. when (pattern == Unbound)
  42. arg != nil
  43. when (pattern.is_a? Regexp)
  44. arg =~ pattern
  45. when (pattern.is_a? Class)
  46. arg.is_a?(pattern)
  47. end
  48. end
  49.  
  50. def fun (name, &block)
  51. if @pattern == nil
  52. raise "You need specify a pattern"
  53. else
  54. @pm_methods = [] if @pm_methods == nil
  55. @pm_methods << {:name=>name ,:block=>block, :pattern=>@pattern}
  56. @pattern = nil
  57. end
  58. end
  59. end
  60. end
Add Comment
Please, Sign In to add comment