2016-07-15 110 views
1

我決定開始玩Prolog(SWI-Prolog)。我寫了一個程序,現在我正在嘗試編寫一個簡單的主謂詞,以便我可以創建一個.exe並從命令行運行該程序。這樣,我可以從命令行找到真實/錯誤的關係,而不是從prolog GUI。但是,我無法理解主謂詞中究竟發生了什麼。以下是節目至今:Prolog中的簡單主謂詞示例

mother(tim, anna). 
mother(anna, fanny). 
mother(daniel, fanny). 
mother(celine, gertrude). 
father(tim, bernd). 
father(anna, ephraim). 
father(daniel, ephraim). 
father(celine, daniel). 

parent(X,Y) :- mother(X,Y). 
parent(X,Y) :- father(X,Y). 
ancestor(X, Y) :- parent(X, Y). 
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y). 

的第一次嘗試:
我把所有的關係定義在一個名爲family_func()。於是斷言,我試圖通過鍵入main調用從主該功能。進入命令行。我希望能夠開始尋找關係像我一樣,我創建的謂詞前,而是在程序啓動與此錯誤:

ERROR: c:/.../ancestor.pl:18:0: Syntax error: Operator expected 

下面是代碼:

family_func():- 
    mother(tim, anna). 
    ... 

    parent(X,Y) :- mother(X,Y). 
    ... 

main:- 
    family_func(). 

第二次嘗試:
我試着把所有的定義放在主謂詞中。我期望能夠輸入main。然後讓程序暫停並等待我開始輸入子句(就像在Java中運行程序並等待用戶輸入一樣)。相反,當我輸入main時,它返回false。

問題1:
我習慣用Java編寫代碼。所以,在我看來,我嘗試的第一件事情應該是工作。我基本上在family_func()中定義了局部變量,然後我調用了更小的「方法」(即parent(X,Y) :- mother(X,Y).),它應該找到這些變量之間的關係。當我打電話給主人時,至少我會希望節目等待我進入關係,返回結果,然後關閉。爲什麼這不起作用?

問題2:
我該如何寫一個主謂語?這樣的程序有沒有好的例子?我試過here這個例子,但是無法啓動它。

感謝您的任何幫助。

編輯:
新的嘗試 - main.返回false,並運行main.返回false即使它應該是真實的之後運行parent(tim, anna).

:- dynamic mother/2. 
:- dynamic father/2. 

family_func:- 
    assert(mother(tim, anna)). 
    assert(father(tim, bernd)). 

parent(X,Y) :- mother(X,Y). 
parent(X,Y) :- father(X,Y). 
ancestor(X, Y) :- parent(X, Y). 
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y). 

main:- 
    family_func. 

編輯:
萬一其他人需要知道,在回答下評論@CapelliC狀態,需要有電話之間的逗號。例如:

family_func:- 
    assert(mother(tim, anna)), 
    assert(mother(anna, fanny)), 
    assert(mother(daniel, fanny)), 
    assert(mother(celine, gertrude)), 
    assert(father(tim, bernd)), 
    assert(father(anna, ephraim)), 
    assert(father(daniel, ephraim)), 
    assert(father(celine, daniel)). 
+2

一個意見:考慮使用'mother_child/2','father_child/2'和'parent_of/2 '清楚地表示每個論點的含義。這會使你的代碼更易讀**,更容易爲你和其他人考慮。這個語法錯誤源於嘗試將一個謂詞的定義嵌入到另一個謂詞中,這是不可能的。 – mat

回答

2

我認爲應該(不允許空參數列表)上的命名

:- dynamic mother/2. 
... other dynamically defined relations... 

family_func:- 
    assert(mother(tim, anna)). 
    ... 

% rules can be dynamic as well, it depends on your application flow... 
parent(X,Y) :- mother(X,Y). 
    ... 

main:- 
    family_func. 
+0

嗨。感謝您的回覆。一旦我運行main,我仍然遇到運行命令的麻煩。當我打電話給main時,它會打印錯誤。然後,如果我嘗試跑父母(蒂姆,安娜)。在main之後,我得到這個錯誤:ERROR:parent/2:Undefined procedure:mother/2 Exception:(8)mother(tim,anna)? – JustBlossom

+0

你忘了': - 動態母親/ 2.'聲明? – CapelliC

+0

在我剛剛解釋的錯誤版本中,我將其排除了。那是因爲當我使用動態時,一切都返回false。我將我在編輯中嘗試的內容放到了我的問題中。 – JustBlossom