2012-07-15 74 views
3

我想通過JPL進行查詢以在java中使用Prolog,我閱讀文檔(http://www.swi-prolog.org/packages/jpl/java_api/getting_started.html) Prolog的謂詞是這些:用JPL查詢Prolog變量

child_of(joe, ralf). 
child_of(mary, joe). 
child_of(steve, joe). 
child_of(steve, ralf). 

descendent_of(X, Y) :- 
    child_of(X, Y). 
descendent_of(X, Y) :- 
    child_of(Z, Y), 
descendent_of(X, Z). 

我的代碼看起來像這樣

Variable X = new Variable(); 

     Query q4 = 
      new Query(
       "descendent_of", 
       new Term[] {X,new Atom("joe")} 
      ); 

     java.util.Hashtable solution; 

     while (q4.hasMoreSolutions()){ 
      solution = q4.nextSolution(); 
      System.out.println("X = " + solution.get(X)); 
     } 

根據我的序言謂詞,我的Java代碼應該找回「瑪麗」和「史蒂夫」,但我得到這個:

X = null 
X = null 

我在做什麼錯了?在此先感謝

編輯:這是我的整個測試

Query q1 = 
    new Query(
     "consult", 
     new Term[] {new Atom("C:\\Users\\cardozo\\Documents\\fer\\info2\\lore\\test.pl")} 
    ); 

return q1; 

System.out.println("consult " + (q.query() ? "succeeded" : "failed")); 

Query q2 = 
    new Query(
     "child_of", 
     new Term[] {new Atom("joe"),new Atom("X")} 
    ); 
Boolean resp= q2.query(); 
System.out.println("child_of(joe,X) is " + resp.toString() 
); 

Query q3 = 
    new Query(
     "descendent_of", 
     new Term[] {new Atom("steve"),new Atom("ralf")} 
    ); 

System.out.println(
    "descendent_of(joe,ralf) is " + 
    (q3.query() ? "provable" : "not provable") 
); 

Variable X = new Variable(); 

Query q4 = 
    new Query(
     "descendent_of", 
     new Term[] {X,new Atom("joe")} 
    ); 

java.util.Hashtable solution; 

q4.query(); 

while (q4.hasMoreSolutions()){ 
    solution = q4.nextSolution(); 
    System.out.println("X = " + solution.get("X")); 
} 

這是我在我的Java控制檯中看到的結果

run: 
% C:\Users\cardozo\Documents\fer\info2\lore\test.pl compiled 0.00 sec, 8 clauses 
consult succeeded 
child_of(joe,X) is false 
descendent_of(joe,ralf) is provable 
X = null 
X = null 
BUILD SUCCESSFUL (total time: 0 seconds) 
+0

我沒有看到你填ŧ他數據庫。請參閱該頁面上的**諮詢**。 – 2012-07-15 19:20:29

+0

@JoopEggen諮詢不僅僅是爲了打開prolog文件嗎?我以前使用該頁面中列出的Query類打開我的pl文件。 – 2012-07-15 19:58:19

回答

2

我會嘗試通過名字來獲取變量:

solution.get("X") 

ed它

與像

查詢Q4 =新查詢( 「descendent_of(X,JOE)」)

+0

也不起作用,我在我的問題 – 2012-07-15 20:07:53

+0

中添加了我的整個代碼,對於延遲抱歉,我在設置JPL – CapelliC 2012-07-15 21:44:16

+0

中遇到了一些小問題,謝謝,這是比我的更好的解決方案 – 2012-07-15 21:49:09

3

我找到了解決方案,我必須使用該類化合物文字查詢(包括在JPL )這樣

Query q4 = new Query(new Compound("descendent_of", new Term[] { new Variable("X"), new Atom("joe")})); 

while (q4.hasMoreSolutions()){ 
      solution = q4.nextSolution(); 
      System.out.println("X = " + solution.get("X")); 
     } 

我也得到了解決

X = mary 
X = steve