@@ -914,11 +914,11 @@ def fetch_rules_for_goal(self, goal):
914
914
def fol_fc_ask (KB , alpha ):
915
915
"""A simple forward-chaining algorithm. [Figure 9.3]"""
916
916
# TODO: Improve efficiency
917
- def enum_subst ( KB ):
918
- kb_vars = list ({ v for clause in KB . clauses for v in variables ( clause )})
919
- kb_consts = list ({c for clause in KB . clauses for c in constant_symbols (clause )})
920
- for assignment_list in itertools .product (kb_consts , repeat = len (kb_vars )):
921
- theta = {x : y for x , y in zip (kb_vars , assignment_list )}
917
+ kb_consts = list ({ c for clause in KB . clauses for c in constant_symbols ( clause )})
918
+ def enum_subst ( p ):
919
+ query_vars = list ({v for clause in p for v in variables (clause )})
920
+ for assignment_list in itertools .product (kb_consts , repeat = len (query_vars )):
921
+ theta = {x : y for x , y in zip (query_vars , assignment_list )}
922
922
yield theta
923
923
924
924
# check if we can answer without new inferences
@@ -931,16 +931,13 @@ def enum_subst(KB):
931
931
new = []
932
932
for rule in KB .clauses :
933
933
p , q = parse_definite_clause (rule )
934
- for theta in enum_subst (KB ):
935
- if any ([set (subst (theta , p )) == set (subst (theta , p_ ))
936
- for p_ in itertools .combinations (KB .clauses , len (p ))]):
934
+ for theta in enum_subst (p ):
935
+ if set (subst (theta , p )).issubset (set (KB .clauses )):
937
936
q_ = subst (theta , q )
938
937
if all ([unify (x , q_ , {}) is None for x in KB .clauses + new ]):
939
- print ('Added' , q_ )
940
938
new .append (q_ )
941
939
phi = unify (q_ , alpha , {})
942
940
if phi is not None :
943
- print (q_ , alpha )
944
941
yield phi
945
942
if not new :
946
943
break
@@ -1000,6 +997,16 @@ def fol_bc_and(KB, goals, theta):
1000
997
'Enemy(Nono, America)'
1001
998
]))
1002
999
1000
+ smalltest_kb = FolKB (
1001
+ map (expr , ['Human(Mary)' ,
1002
+ 'Female(x) ==> Likes(x, Chocolate)' ,
1003
+ 'Male(x) ==> Likes(x, IceCream)' ,
1004
+ 'Wife(x, y) & Human(x) ==> Female(x)' ,
1005
+ 'Wife(y, x) & Human(x) ==> Male(x)' ,
1006
+ 'Human(John)' ,
1007
+ 'Wife(Mary, John)'
1008
+ ]))
1009
+
1003
1010
# ______________________________________________________________________________
1004
1011
1005
1012
# Example application (not in the book).
0 commit comments