Last active
August 29, 2015 14:11
-
-
Save esehara/55427f08b21ee90d580a to your computer and use it in GitHub Desktop.
General Problem Solver ver.01 『実践Common Lisp』より
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
===> [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