Module: Factbase::Term::Logical

Included in:
Factbase::Term
Defined in:
lib/factbase/terms/logical.rb

Overview

Logical terms.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Instance Method Details

#_only_bool(val, pos) ⇒ Object



96
97
98
99
100
101
# File 'lib/factbase/terms/logical.rb', line 96

def _only_bool(val, pos)
  val = val[0] if val.is_a?(Array)
  return false if val.nil?
  return val if val.is_a?(TrueClass) || val.is_a?(FalseClass)
  raise "Boolean expected, while #{val.class} received from #{@operands[pos]}"
end

#always(_fact, _maps) ⇒ Object



31
32
33
34
# File 'lib/factbase/terms/logical.rb', line 31

def always(_fact, _maps)
  assert_args(0)
  true
end

#and(fact, maps) ⇒ Object



53
54
55
56
57
58
# File 'lib/factbase/terms/logical.rb', line 53

def and(fact, maps)
  (0..@operands.size - 1).each do |i|
    return false unless _only_bool(the_values(i, fact, maps), i)
  end
  true
end

#and_or_simplifyObject



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/factbase/terms/logical.rb', line 74

def and_or_simplify
  strs = []
  ops = []
  @operands.each do |o|
    o = o.simplify
    s = o.to_s
    next if strs.include?(s)
    strs << s
    ops << o
  end
  return ops[0] if ops.size == 1
  Factbase::Term.new(@op, ops)
end

#and_simplifyObject



88
89
90
# File 'lib/factbase/terms/logical.rb', line 88

def and_simplify
  and_or_simplify
end

#either(fact, maps) ⇒ Object



67
68
69
70
71
72
# File 'lib/factbase/terms/logical.rb', line 67

def either(fact, maps)
  assert_args(2)
  v = the_values(0, fact, maps)
  return v unless v.nil?
  the_values(1, fact, maps)
end

#never(_fact, _maps) ⇒ Object



36
37
38
39
# File 'lib/factbase/terms/logical.rb', line 36

def never(_fact, _maps)
  assert_args(0)
  false
end

#not(fact, maps) ⇒ Object



41
42
43
44
# File 'lib/factbase/terms/logical.rb', line 41

def not(fact, maps)
  assert_args(1)
  !_only_bool(the_values(0, fact, maps), 0)
end

#or(fact, maps) ⇒ Object



46
47
48
49
50
51
# File 'lib/factbase/terms/logical.rb', line 46

def or(fact, maps)
  (0..@operands.size - 1).each do |i|
    return true if _only_bool(the_values(i, fact, maps), i)
  end
  false
end

#or_simplifyObject



92
93
94
# File 'lib/factbase/terms/logical.rb', line 92

def or_simplify
  and_or_simplify
end

#when(fact, maps) ⇒ Object



60
61
62
63
64
65
# File 'lib/factbase/terms/logical.rb', line 60

def when(fact, maps)
  assert_args(2)
  a = @operands[0]
  b = @operands[1]
  !a.evaluate(fact, maps) || (a.evaluate(fact, maps) && b.evaluate(fact, maps))
end