Learn Prolog Now!第一章,第四節,實踐課

1.4 實踐課

不要認爲實踐課不重要;實踐課絕對是最重要的。讀文本,做練習,這不足以讓你成爲一個prolog程序員。想真正掌握這門語言,你需要長時間坐在電腦前和prolog一起“玩”!

第一次的實踐課想讓你熟悉,創建和運行簡單prolog程序的基礎知識。但是,因爲prolog有不同的版本,運行的操作系統也五花八門,我們無法盡善盡美。我們要做的是用通俗的語言描述prolog運行的時候,發生了什麼,還會列出你需要掌握的實用技能,再給你一些建議。

運行prolog程序的最簡單的方法如下:

你需要一個存有prolog程序的文件(如kb2.pl)。打開prolog,prolog會出現提示符(表示可以開始查詢了):

?-

到這一步,prolog還完全不知道KB2的存在。不相信的話可以用listing命令查看:

?-  listing.

listing命令是一個prolog內建的斷言,用來讓prolog顯示當前所有知識庫的內容。但prolog裏沒有任何知識庫,所以顯示:

yes

更準確的說:prolog從知識庫知道的東西爲空,所以它顯示了空,接着顯示了yes。事實上,在一些更先進的版本中可能會顯示一些內容(比如載入的庫的名字,庫會在第12章講到),但是無論如何,其本意都是“我沒發現任何知識庫”

要把KB2告訴prolog,確保當前目錄下有kb2.pl,輸入:

 ?-  [kb2].

這句話的意思是讓prolog來尋找並載入kb2.pl。如果文件沒有錯誤,prolog會讀入,可能會輸出一些文件信息,然後說:

yes

prolog文件以.pl爲後綴,一般prolog尋找文件不必輸入.pl。但這也有個問題,就是Perl 腳本的後綴也是.pl。現在也還有很多Perl腳本在使用中,這可能會導致一些問題。這就是生活吧(C’est la vie)。

如果上述問題不存在,但是你在輸入[kb2]後,prolog報錯,說程序不存在,那麼你很可能沒有在kb2.pl文件位置打開prolog。若你不想在文件位置重啓prolog,你可以輸入文件路徑:

?-  [’c:/Documents  and  Settings/kris/Prolog/kb2.pl’].

至此,prolog應該已經知道了kb2裏的所有斷言。我們可以再用listing命令來確認:

    ?-  listing.

    % file: C:/CODE/prolog/kb1.pl

   listens2Music(mia). 
   happy(yolanda). 
   playsAirGuitar(mia):- 
         listens2Music(mia). 
   playsAirGuitar(yolanda):- 
         listens2Music(yolanda). 
   listens2Music(yolanda):- 
             happy(yolanda). 

    yes

對了,listing也可以這樣用:

   ?-  listing(playsAirGuitar).
   
   playsAirGuitar(mia):- 
         listens2Music(mia). 
   playsAirGuitar(yolanda):- 
         listens2Music(yolanda). 
    
   yes

接下來我們來總結一些使用技能:

譯者注:可能是因爲時代的原因,作者寫的這些技能就是最基本的電腦操作技能,就不再浪費時間翻譯了。

  • You will need to know some basic facts about the operating system you are using, such as the directory structure it uses. After all, you will need to know how to save the files containing programs where you want them.
  • You will need to know how to use some sort of text editor, in order to write and modify programs. Some Prolog implementations come with built-in text editors, but if you already know a text editor (such as Emacs) you can use this to write your Prolog code. Just make sure that you save your files as simple text files (for example, if you are working under Windows, don’t save them as Word documents).
  • You may want to take example Prolog programs from the internet. So make sure you know how to use a browser to find what you want, and to store the code where you want it.
  • You need to know how to start your version of Prolog, and how to consult files with it.

The sooner you pick up these skills, the better. With them out of the way (which shouldn’t take long) you can start concentrating on mastering Prolog (which will take longer).

在搞定了這些技能以後幹什麼?好好玩prolog啊!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章