Prolog 程序的元素

目錄 下頁

我們使用以下樣本程序去解釋 Prolog 程序的結構。

程序一︰一個樣本 Prolog 程序
sunny.                  /* 晴天。 */
father(john, peter).   
/* John 是 Peter 的父親。 */
father(john, mary).
father(david, liza).
father(david, john).
father(jack, susan).
father(jack, ray).
mother(susan, peter).  
/* Susan 是 Peter 的母親。 */
mother(susan, mary).
mother(amy, liza).
mother(amy, john).
mother(karen, susan).
mother(karen, ray).
loves(john, susan).    
/* John 愛 Susan。 */
b1([p, 2, q], p).      
/* 沒有特別的意思。 */

yeye(X, Y) :- father(X, Temp), father(Temp, Y).
        /* 如果 X 是 Temp 的父親,而 Temp 是 Y 的父親的話,
           那麼 X 是 Y 的「yeye」。 */
mama(X, Y) :- mother(X, Temp), father(Temp, Y).
gunggung(X, Y) :- father(X, Temp), mother(Temp, Y).
popo(X, Y) :- mother(X, Temp), mother(Temp, Y).
a(A1, [A | B]) :- A1 is A + 1.
a(A, [B | C]) :- a(A, C).father(john, peter).

從上面可見,一個 Prolog 程序包含數個短句,每一個短句以英文句號(.)結尾。每一個短句是事實或者是規則

一個原子是一堆英數字符(底線字符 _ 也被當作是英數字符),由一個小楷字母開始。在以上的例子中, fathermotherdavidyeyeb1pa 等等都是原子。有些原子是常數,而其他的是謂詞。

一個變量是一堆英數字符,由一個大楷字母或底線字符(_)開始。在以上的例子中,XTempYA1ABC 是變量。在 Prolog 中,變量和常數不用宣告。

常數及變量被稱為用語

大小寫字母在 Prolog 是不同的。因此 abcaBc 兩個不同的東西(即使它們都是原子)。

除了原子及變量,Prolog 也可以處理數字。

原子、變量及數子可以用方括號([])包著,組成一個列表。

註釋以「/*」及「*/」包著。

目錄 下頁