Class: Rbprolog::Context

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeContext

Returns a new instance of Context.



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

def initialize
  @scopes = []
  @binds = {}
end

Instance Attribute Details

#bindsObject

Returns the value of attribute binds.



3
4
5
# File 'lib/rbprolog/context.rb', line 3

def binds
  @binds
end

Instance Method Details

#[](sym) ⇒ Object



24
25
26
# File 'lib/rbprolog/context.rb', line 24

def [](sym)
  @binds[sym]
end

#[]=(sym, value) ⇒ Object



28
29
30
# File 'lib/rbprolog/context.rb', line 28

def []=(sym, value)
  @binds[sym] = value
end

#deduce(v) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rbprolog/context.rb', line 32

def deduce(v)
  if Var === v
    unless @binds[v.sym]
      @scopes.last << v.sym
      @binds[v.sym] = Var.new(v.sym)
    end

    @binds[v.sym]
  else
    v
  end
end

#match!(v1, v2) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/rbprolog/context.rb', line 15

def match!(v1, v2)
  if match?(v1, v2)
    @binds[v1.sym] = v2 if Var === v1 && !(Var === v2)
    true
  else
    false
  end
end

#match?(v1, v2) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
13
# File 'lib/rbprolog/context.rb', line 10

def match?(v1, v2)
  v1 = deduce(v1)
  Var === v1 || Var === v2 || v1 == v2
end

#scope(predicate, &block) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rbprolog/context.rb', line 45

def scope(predicate, &block)
  @scopes.push([])

  mirror = @binds.clone

  result = yield predicate.args.map {|arg| self.deduce(arg)}

  @scopes.pop.each {|bind| @binds.delete bind}
  @binds.merge!(mirror)

  result
end