Class: Factbase::Term

Inherits:
Object
  • Object
show all
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))
Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024 Yegor Bugayenko

License

MIT

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(operator, operands) ⇒ Term

Ctor.

Parameters:

  • operator (Symbol)

    Operator

  • operands (Array)

    Operands



48
49
50
51
# File 'lib/factbase/term.rb', line 48

def initialize(operator, operands)
  @op = operator
  @operands = operands
end

Instance Attribute Details

#opObject (readonly)

Returns the value of attribute op.



43
44
45
# File 'lib/factbase/term.rb', line 43

def op
  @op
end

#operandsObject (readonly)

Returns the value of attribute operands.



43
44
45
# File 'lib/factbase/term.rb', line 43

def operands
  @operands
end

Instance Method Details

#evaluate(fact, maps) ⇒ bool

Does it match the fact?

Parameters:

Returns:

  • (bool)

    TRUE if matches



57
58
59
60
61
# File 'lib/factbase/term.rb', line 57

def evaluate(fact, maps)
  send(@op, fact, maps)
rescue NoMethodError => e
  raise "Term '#{@op}' is not defined: #{e.message}"
end

#simplifyFactbase::Term

Simplify it if possible.

Returns:



65
66
67
68
69
70
71
72
# File 'lib/factbase/term.rb', line 65

def simplify
  m = "#{@op}_simplify"
  if respond_to?(m, true)
    send(m)
  else
    self
  end
end

#to_sString

Turns it into a string.

Returns:

  • (String)

    The string of it



76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/factbase/term.rb', line 76

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