我已经实现了几个链规则,以便最后一条规则根据前一条规则的结果获得所需的结果。
rule1(X,Y) :-
pred1(X,Z),
pred1(Y,Z).
rule2(Z,T) :-
rule1(X,Y),
pred2(Z,X),
pred2(T,Y).
我需要获得每个规则推断的每个事实。我是使用jpl库从Java做的。
String stringFileQuery = "rule1(X,Y)";
System.out.println(stringFileQuery + " "
+ (Query.hasSolution(stringFileQuery) ? "succeeded" : "failed"));
Query fileQuery = new Query(stringFileQuery);
System.out.println("all solutions of " + stringFileQuery);
while (fileQuery.hasMoreSolutions()) {
Map<String, Term> s10 = fileQuery.nextSolution();
System.out.println("First -> " + s10.get("X") + ", Second ->" + 10.get("Y"));
}
即使在Prolog中,我怎样才能获得所有这些事实?在真实的程序中,我有两个以上的规则。
答案 0 :(得分:1)
你在这里寻找的是Prolog的meta-interpreter,它记录了事实。由于Prolog是一种homoiconic语言,因此编写一个简单的元解释器是trivial。
您可能希望使用clause_property/2
检查您正在检查的条款是否是事实,如此
recordFacts(Goal, [Goal|Facts]) :-
clause(Goal, _Body, Ref),
clause_property(Ref, fact).
一个完整的例子就像是
recordFacts(Goal, Facts) :-
recordFacts(Goal, [], AllFacts),
list_to_set(AllFacts, Facts).
recordFacts((Goal, RestOfGoals), FactsIn, FactsOut) :-
recordFacts(Goal, FactsIn, FactsH),
recordFacts(RestOfGoals, FactsH, FactsOut).
recordFacts(Goal, Facts, [Goal|Facts]) :-
clause(Goal, _, Ref),
clause_property(Ref, fact).
recordFacts(Goal, FactsIn, FactsOut) :-
clause(Goal, Body, Ref),
not(clause_property(Ref, fact)),
not(clause_property(Ref, predicate(system: (',')/2))),
recordFacts(Body, FactsIn, FactsOut).