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の実行は以下のように行われる。
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.
?-
以下ではエラーとなる。
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をインタラクティブシェル上で実行して定義できるかのような書き方がされているが、それをやるとエラーに見舞われる、という話。バージョンか何かが違うんだろう。
よって、インタラクティブシェルに直接コードを載せたい場合は以下のような書き方となる。
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 )" ) "