Class: Pattern

Inherits:
Object
  • Object
show all
Defined in:
lib/Olib/pattern.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cases) ⇒ Pattern

Returns a new instance of Pattern.



7
8
9
# File 'lib/Olib/pattern.rb', line 7

def initialize(cases)
  @cases = cases
end

Instance Attribute Details

#casesObject

Returns the value of attribute cases.



5
6
7
# File 'lib/Olib/pattern.rb', line 5

def cases
  @cases
end

Instance Method Details

#match(str) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/Olib/pattern.rb', line 11

def match(str)
  found = @cases.each_pair.find do |exp, handler|
    str =~ exp
  end

  if !found
    raise Exception.new [
      "Error: inexhaustive pattern",
      "counterexample: #{str}",
    ].join("\n")
  end

  exp, handler = found

  handler.call exp.match(str).to_struct
end

#to_procObject



28
29
30
31
32
33
# File 'lib/Olib/pattern.rb', line 28

def to_proc
  patt = self
  Proc.new do |str|
    patt.match str
  end
end