位元詩人 技術雜談:Perl x Prolog in AI::Prolog

Facebook Twitter LinkedIn LINE Skype EverNote GMail Yahoo Email

Perl programming can be done in imperative, objective and functional styles. However, Perl lacks direct support in logic programming. Prolog is a logic programming language, popular in the fields of natural language processing and artificial intelligence. AI::Prolog is where Perl and Prolog cross.

AI::Prolog is a Prolog compiler written purely in Perl and, optionally, comes with aiprolog, a interactive Prolog interface. The module is easy to use if you know how to write Prolog code. For newcomers of Prolog, see Learn Prolog Now! or Adventure in Prolog. You may install a real Prolog compiler to evaluate your code.

To write Prolog code in Perl script, you need to initiate a knowledge base or database. (Don't be confused with relational databases like MySQL or PostgreSQL.)


use AI::Prolog;
use Data::Dumper;

my $database = <<"END_PROLOG";
directTrain(saarbruecken,dudweiler).
directTrain(forbach,saarbruecken).
directTrain(freyming,forbach).
directTrain(stAvold,freyming).
directTrain(fahlquemont,stAvold).
directTrain(metz,fahlquemont).
directTrain(nancy,metz).

travelFromTo(X,Y) :- directTrain(X,Y).
travelFromTo(X,Z) :-
    directTrain(X,Y),
    travelFromTo(Y,Z).
END_PROLOG

my $prolog = AI::Prolog->new($database);
{{< / highlight >}}

Then, query the knowledge base.

```perl
$prolog->query("travelFromTo(metz,Y).");
{{< / highlight >}}

Finally, print out the results.  The results will be an array reference.  The first value holds the functor name; the others are atoms.  By this way, the results of Prolog code can be re-used by Perl scripts.

```perl
while (my $result = $prolog->results) {
    # $result is similiar to ['travelFromTo', 'metz', 'fahlquemont'];
    print "@{$result}\n";
}
{{< / highlight >}}

Since AI::Prolog is implemented in Perl, the speed is not fast and the author of AI::Prolog does not recommend the use of AI::Prolog on production use.  For better performance, you may check out [Language::Prolog::Yaswi](https://metacpan.org/pod/Language::Prolog::Yaswi).
關於作者

位元詩人 (ByteBard) 是資訊領域碩士,專注於從探索到產品的開發過程,並以工具驅動的方式改善專案。喜歡以開源專案作為成果,回饋社群。

主要方向包括:自用工具的打磨 (dogfooding)、編譯器技術在工具開發中的應用,以及將研究轉化為可維護的開源成果。

除了技術之外,也喜歡日本料理和黑咖啡,偶爾自助旅行,將生活中的靈感融入技術隨筆。