プログラミング

Prolog言語で論理プログラミング入門・Prologのインストール方法・サンプルコード・使い方

prologは論理プログラミング言語と呼ばれる、PythonやJavaScriptをはじめとした流行のプログラミング言語とは大きく異なる特性を持ったプログラミング言語のひとつである。prologは形式論理の一階述語論理に倣っている。

# install prolog on ubuntu
sudo apt update ; sudo apt-get install swi-prolog

The basic constructs of logic programming, terms and statements, are inherited from logic. There are three basic statements:

Facts are fundamental assertions about the problem domain (e.g. “Socrates is a man”)
Rules are inferences about facts in the domain (e.g. “All men are mortal.“)
Queries are questions about that domain (e.g. “Is Socrates mortal?“)

上記の通り、prologのコードにはFacts Rules Queriesの3つの属性がある。
大雑把に言って、factsは真実であること、rulesは真実に関連する事柄、queriesは質問である。

Introduction to logic programming with Prolog

prologの実行は以下のように行われる。

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_3e65d686-900b-4903-9416-c2ea5fdb7d2f.png

yuis@yuis:~/pg/prolog$ cat > dev.pl
man(socrates).
mortal(X) :- man(X).
yuis@yuis:~/pg/prolog$ prolog -q
?- mortal(socrates).
ERROR: Undefined procedure: mortal/1 (DWIM could not correct goal)
?- [dev].
true.

?- mortal(socrates).
true.

?-

以下ではエラーとなる。

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_d677592f-854a-437c-b49e-86b100533044.png

yuis@yuis:~/pg/prolog$ prolog -q
?- man(socrates).
ERROR: Undefined procedure: man/1 (DWIM could not correct goal)
?-

何が言いたいかというと、factsとrulesに関してはファイルにて記述しそれを読み込み、queriesに関してはインタラクティブシェル上で実行する、という方法を取るべきである、ということ。

Loading files in Prolog – Stack Overflow

多くのprolog参考記事を見てみると、man(socrates).といったfactsをインタラクティブシェル上で実行して定義できるかのような書き方がされているが、それをやるとエラーに見舞われる、という話。バージョンか何かが違うんだろう。

よって、インタラクティブシェルに直接コードを載せたい場合は以下のような書き方となる。

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_eaa31ad9-370b-4fb1-af40-ae17ce4baafd.png

yuis@yuis:~/pg/prolog$ prolog -q <<< " $( printf "[dev].\nmortal(socrates)." )"
true.

true.

個人的なやり方を紹介すると、ファイルを2つ用意して、factsとrulesのファイル、queriesのファイルとわけて以下のようにしてやっている。

prolog <<< " $( printf "[dev_facts].\n$( cat dev_queries.pl )" ) "

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です