Instantly share code, notes, and snippets.

@esehara /gps.rb
Last active Aug 29, 2015

Embed
What would you like to do?
General Problem Solver ver.01 『実践Common Lisp』より
class Operator < Struct.new(:action, :preconds, :addlist, :dellist)
def appropriate? goal
self.addlist.include? goal
end
def to_s
self.action.to_s.gsub('_', ' ')
end
end
class GPS
attr_accessor :state
def initialize state, ops
@state = state
@ops = ops
end
def solve? goals
puts "===> [Start] "
results = goals.all? { |goal| archive? goal }
puts "<=== [End]"
return results
end
def match_operators goal
@ops.select { |op| op.appropriate? goal }
end
def archive? goal
apply_result = match_operators(goal).any? { |op| apply! op }
@state.include?(goal) || !!(apply_result)
end
def apply! op
if op.preconds.all? {|precond| archive? precond}
puts "Do: #{op}"
@state = op.dellist.to_a + @state
@state = op.addlist.to_a + @state
true
end
false
end
end
testdata = [Operator.new(:drive_son_to_school,
[:son_at_home, :car_works],
[:son_at_school],
[:son_at_home]),
Operator.new(:shop_installs_battery,
[:car_needs_battery, :shop_knows_problem, :shop_has_money],
[:car_works]),
Operator.new(:tell_shop_problem,
[:in_communication_with_shop],
[:shop_knows_problem]),
Operator.new(:telephone_shop,
[:know_phone_number],
[:in_communication_with_shop]),
Operator.new(:look_up_number,
[:have_phone_book],
[:know_phone_number]),
Operator.new(:give_shop_money,
[:have_money],
[:shop_has_money],
[:have_money])]
gps2 = GPS.new([:son_at_home, :car_needs_battery, :have_money, :have_phone_book],
testdata)
p gps2.solve? [:son_at_school]
===> [Start]
Do: look up number
Do: telephone shop
Do: tell shop problem
Do: give shop money
Do: shop installs battery
Do: drive son to school
<=== [End]
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment