class RubyProlog::Environment

Public Class Methods

new() click to toggle source
# File lib/ruby-prolog/ruby-prolog.rb, line 186
def initialize
  @table = {}
end

Public Instance Methods

[](t) click to toggle source
# File lib/ruby-prolog/ruby-prolog.rb, line 234
def [](t)
  t, env = dereference(t)
  return case t
         when Goal then Goal.new(t.pred_id, t.pred_name, env[t.args])
         when Cons then Cons.new(env[t[0]], env[t[1]])
         when Array then t.collect {|e| env[e]}
         else t
         end
end
clear() click to toggle source
# File lib/ruby-prolog/ruby-prolog.rb, line 202
def clear
  @table.clear
end
delete(x) click to toggle source
# File lib/ruby-prolog/ruby-prolog.rb, line 198
def delete(x)
  @table.delete(x) {|k| raise "#{k} not found in #{inspect}"}
end
dereference(t) click to toggle source
# File lib/ruby-prolog/ruby-prolog.rb, line 224
def dereference(t)
  env = self
  while Symbol === t
    p = env.get(t)
    break if p.nil?
    t, env = p
  end
  return [t, env]
end
get(x) click to toggle source
# File lib/ruby-prolog/ruby-prolog.rb, line 194
def get(x)
  return @table[x]
end
put(x, pair) click to toggle source
# File lib/ruby-prolog/ruby-prolog.rb, line 190
def put(x, pair)
  @table[x] = pair
end
solution() click to toggle source
# File lib/ruby-prolog/ruby-prolog.rb, line 206
def solution
  @table.map do |var, env|
    xp = env
    loop {
      x, x_env = xp
      y, y_env = x_env.dereference(x)
      next_xp = y_env.get(x)
      if next_xp.nil?
        xp = [y, y_env]
        break
      else
        xp = next_xp
      end
    }
    [var, xp[0]]
  end.to_h
end