Class: RubyProlog::Environment

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-prolog/ruby-prolog.rb

Instance Method Summary collapse

Constructor Details

#initializeEnvironment

Returns a new instance of Environment.



178
179
180
# File 'lib/ruby-prolog/ruby-prolog.rb', line 178

def initialize
  @table = {}
end

Instance Method Details

#[](t) ⇒ Object



226
227
228
229
230
231
232
233
234
# File 'lib/ruby-prolog/ruby-prolog.rb', line 226

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

#clearObject



194
195
196
# File 'lib/ruby-prolog/ruby-prolog.rb', line 194

def clear
  @table.clear
end

#delete(x) ⇒ Object



190
191
192
# File 'lib/ruby-prolog/ruby-prolog.rb', line 190

def delete(x)
  @table.delete(x) {|k| raise "#{k} not found in #{inspect}"}
end

#dereference(t) ⇒ Object



216
217
218
219
220
221
222
223
224
# File 'lib/ruby-prolog/ruby-prolog.rb', line 216

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) ⇒ Object



186
187
188
# File 'lib/ruby-prolog/ruby-prolog.rb', line 186

def get(x)
  return @table[x]
end

#put(x, pair) ⇒ Object



182
183
184
# File 'lib/ruby-prolog/ruby-prolog.rb', line 182

def put(x, pair)
  @table[x] = pair
end

#solutionObject



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/ruby-prolog/ruby-prolog.rb', line 198

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