Michelle Chen 技術雜談: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";

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

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

Then, query the knowledge base.

{{< / 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.

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).