位元詩人 技術雜談: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) 是資訊領域碩士,喜歡用開源技術來解決各式各樣的問題。這類技術跨平台、重用性高、技術生命長。

除了開源技術以外,位元詩人喜歡日本料理和黑咖啡,會一些日文,有時會自助旅行。