Class: Factbase::Term
- Inherits:
-
Object
- Object
- Factbase::Term
- Defined in:
- lib/factbase/term.rb
Overview
Term.
This is an internal class, it is not supposed to be instantiated directly.
It is possible to use for testing directly, for example to make a term with two arguments:
require 'factbase/fact'
require 'factbase/term'
f = Factbase::Fact.new(Mutex.new, { 'foo' => [42, 256, 'Hello, world!'] })
t = Factbase::Term.new(:lt, [:foo, 50])
assert(t.evaluate(f))
The design of this class may look ugly, since it has a large number of methods, each of which corresponds to a different type of a Term
. A much better design would definitely involve many classes, one per each type of a term. It’s not done this way because of an experimental nature of the project. Most probably we should keep current design intact, since it works well and is rather simple to extend (by adding new term types). Moreover, it looks like the number of possible term types is rather limited and currently we implement most of them.
- Author
-
Yegor Bugayenko ([email protected])
- Copyright
-
Copyright © 2024 Yegor Bugayenko
- License
-
MIT
Instance Attribute Summary collapse
-
#op ⇒ Object
readonly
Returns the value of attribute op.
-
#operands ⇒ Object
readonly
Returns the value of attribute operands.
Instance Method Summary collapse
-
#evaluate(fact, maps) ⇒ bool
Does it match the fact?.
-
#initialize(operator, operands) ⇒ Term
constructor
Ctor.
-
#simplify ⇒ Factbase::Term
Simplify it if possible.
-
#to_s ⇒ String
Turns it into a string.
Constructor Details
#initialize(operator, operands) ⇒ Term
Ctor.
57 58 59 60 |
# File 'lib/factbase/term.rb', line 57 def initialize(operator, operands) @op = operator @operands = operands end |
Instance Attribute Details
#op ⇒ Object (readonly)
Returns the value of attribute op.
52 53 54 |
# File 'lib/factbase/term.rb', line 52 def op @op end |
#operands ⇒ Object (readonly)
Returns the value of attribute operands.
52 53 54 |
# File 'lib/factbase/term.rb', line 52 def operands @operands end |
Instance Method Details
#evaluate(fact, maps) ⇒ bool
Does it match the fact?
66 67 68 69 70 71 72 |
# File 'lib/factbase/term.rb', line 66 def evaluate(fact, maps) send(@op, fact, maps) rescue NoMethodError => e raise "Term '#{@op}' is not defined at #{self}: #{e.}" rescue StandardError => e raise "#{e.} at #{self} (#{e.backtrace[0]})" end |
#simplify ⇒ Factbase::Term
Simplify it if possible.
76 77 78 79 80 81 82 83 |
# File 'lib/factbase/term.rb', line 76 def simplify m = "#{@op}_simplify" if respond_to?(m, true) send(m) else self end end |
#to_s ⇒ String
Turns it into a string.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/factbase/term.rb', line 87 def to_s items = [] items << @op items += @operands.map do |o| if o.is_a?(String) "'#{o.gsub("'", "\\\\'").gsub('"', '\\\\"')}'" elsif o.is_a?(Time) o.utc.iso8601 else o.to_s end end "(#{items.join(' ')})" end |