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.



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

def initialize
  @table = {}
end

Instance Method Details

#[](t) ⇒ Object



234
235
236
237
238
239
240
241
242
# 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

#clearObject



202
203
204
# File 'lib/ruby-prolog/ruby-prolog.rb', line 202

def clear
  @table.clear
end

#delete(x) ⇒ Object



198
199
200
# 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) ⇒ Object



224
225
226
227
228
229
230
231
232
# 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) ⇒ Object



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

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

#put(x, pair) ⇒ Object



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

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

#solutionObject



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# 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