位元詩人 技術雜談: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) 認為開發應用程式的目的是為社會帶來價值。如果在這個過程中該軟體能成為永續經營的項目,那就是開發者和使用者雙贏的局面。

位元詩人喜歡用開源技術來解決各式各樣的問題,但必要時對專有技術也不排斥。閒暇之餘,位元詩人將所學寫成文章,放在這個網站上和大家分享。