PerlでProlog

PerlのAI::Prologを入れてほんの少し触ったけど面白い。

 AI::Prolog is merely a convenient wrapper for a pure Perl Prolog compiler.
 Regrettably, at the current time, this requires you to know Prolog.  That will
 change in the future.

PerlPrologできるよ!

CPANのSYNOPSISの実行例を書いておきます。
SYNOPSIS

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

 my $database = <<'END_PROLOG';
   append([], X, X).
   append([W|X],Y,[W|Z]) :- append(X,Y,Z).
 END_PROLOG

 my $prolog = AI::Prolog->new($database);
 
 my $list   = $prolog->list(qw/a b c d/);
 $prolog->query("append(X,Y,[$list]).");
 while (my $result = $prolog->results) {
     print Dumper $result;
 }

実行例

$VAR1 = [
          'append',
          [],
          [
            'a',
            'b',
            'c',
            'd'
          ],
          [
            'a',
            'b',
            'c',
            'd'
          ]
        ];
$VAR1 = [
          'append',
          [
            'a'
          ],
          [
            'b',
            'c',
            'd'
          ],
          [
            'a',
            'b',
            'c',
            'd'
          ]
        ];
$VAR1 = [
          'append',
          [
            'a',
            'b'
          ],
          [
            'c',
            'd'
          ],
          [
            'a',
            'b',
            'c',
            'd'
          ]
        ];
$VAR1 = [
          'append',
          [
            'a',
            'b',
            'c'
          ],
          [
            'd'
          ],
          [
            'a',
            'b',
            'c',
            'd'
          ]
        ];
$VAR1 = [
          'append',
          [
            'a',
            'b',
            'c',
            'd'
          ],
          [],
          [
            'a',
            'b',
            'c',
            'd'
          ]
        ];


階乗のプログラム

#!/usr/bin/env perl

use strict;
use warnings;
use AI::Prolog;
use Data::Dumper;

my $database = <<'END_PROLOG';
fact(0, 1).
fact(X, Y) :-
    X > 0,
    X1 is X - 1,
    fact(X1, Y1),
    Y is X * Y1.
END_PROLOG
my $prolog = AI::Prolog->new($database);

$prolog->query("fact(1, Y).");
my $result = $prolog->results;
print "n! = " . $result->[2] . "\n";

$prolog->query("fact(3, Y).");
$result = $prolog->results;
print "n! = " . $result->[2] . "\n";

$prolog->query("fact(9, Y).");
$result = $prolog->results;
print "n! = " . $result->[2] . "\n";

実行例

n! = 1
n! = 6
n! = 362880
vallog: Prolog 階乗


メインのブログにまとめるの忘れるので、こっちにやったこと書いていこうと思います。

「しゃっくりへただね!」っていわれた。
もっといいしゃっくりしたい。