Class: Rbprolog::Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/rbprolog/rule.rb

Overview

when fail at one predicate, the output values need be reset, and remove from the parent rule/s context

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sym, *args, predicates) ⇒ Rule

Returns a new instance of Rule.



7
8
9
10
11
# File 'lib/rbprolog/rule.rb', line 7

def initialize(sym, *args, predicates)
  @sym = sym
  @args = args
  @predicates = [predicates].flatten
end

Instance Attribute Details

#argsObject

Returns the value of attribute args.



5
6
7
# File 'lib/rbprolog/rule.rb', line 5

def args
  @args
end

#symObject

Returns the value of attribute sym.



5
6
7
# File 'lib/rbprolog/rule.rb', line 5

def sym
  @sym
end

Instance Method Details

#deduce_predicates(context, rules, *predicates, tabs, id, &block) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rbprolog/rule.rb', line 29

def deduce_predicates(context, rules, *predicates, tabs, id, &block)
  if predicates.empty?
    yield
  else
    predicate = predicates.shift
    if Deduction === predicate
      predicate.each_deduce(context, rules, tabs + "\t", id + [@predicates.size - predicates.size - 1]) do |hash|
        deduce_predicates(context, rules, *predicates, tabs, id, &block)
      end
    else
      @logic.send(:define_singleton_method, :const_missing) do |sym|
        context.binds[sym]
      end

      predicate.call && deduce_predicates(context, rules, *predicates, tabs, id, &block)
    end

  end
end

#each_deduce(rules, *args, tabs, id) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rbprolog/rule.rb', line 13

def each_deduce(rules, *args, tabs, id)
  print "#{tabs}#{id.join('.')} #{@sym}(#{@args.map(&:to_s).join(', ')}).deduce(#{args.map(&:to_s).join(', ')})"

  context = Context.new
  context.scope(self) do
    if self.match!(context, args)
      puts " => #{@sym}(#{@args.map {|arg| context.deduce(arg).to_s}.join(', ')})" #{context.to_s} #{context.binds.inspect}"

      deduce_predicates(context, rules, *@predicates, tabs, id) do
        yield context.binds
      end
    else
      print "\n"
    end
  end
end

#match!(context, args) ⇒ Object



53
54
55
56
57
# File 'lib/rbprolog/rule.rb', line 53

def match!(context, args)
  match = match?(context, args)
  @args.zip(args).each {|v1, v2| context.match!(v1, v2)} if match
  match
end

#match?(context, args) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/rbprolog/rule.rb', line 49

def match?(context, args)
  @args.size == args.size && @args.zip(args).all? {|v1, v2| context.match?(v1, v2)}
end