Math works! Towers of Hanoi in AI::Prolog

Ovid on 2005-02-23T17:07:15

Well, I couldn't sleep last night. I kept tossing and turning while thinking about how to get math working right. I got up early and rather than implement the complete parser solution, I went ahead and used predicates instead of operators for math. It's clumsy, but it is how Prolog works underneath the hood:

% X is 3 + 4.
is(X, plus(3,4)).
% Once again:  patches welcome :)

The snippet above binds X to 7 (obviously). The predicates I have working are:

plus(X,Y).
minus(X,Y).
mult(X,Y).
div(X,Y).
mod(X,Y).
is(X,Y).
ge(X,Y).
gt(X,Y).
le(X,Y).
lt(X,Y).

Unfortunately, I can only declare integer numbers (though the math supports floats), but that's a limitation of my parser. I'll fix that.

What this means, however, is after some polishing, the Prolog engine is mostly feature complete. Yeah, I can use a new parser, but I'm not too worried about that right now. Instead, since I have the features I want, I can get this ready for distribution and start working on performance. For example, I've written a tiny scheduling program. It's very slow. However, the Towers of Hanoi is very fast :)

#!/usr/bin/perl
use strict;
use warnings;
use AI::Prolog;

my $prolog = AI::Prolog->new(<<'END_PROLOG');
hanoi(N) :-
    move(N, left, center, right).

move(0, NULL1, NULL2, NULL3) :- !.

move(N,A,B,C) :-
    is(M, minus(N,1)),
    move(M,A,C,B),
    inform(A,B),
    move(M,C,B,A).

inform(X,Y) :-
    print("Move a disc from the "),
    print(X),
    print(" pole to the "),
    print(Y),
    println(" pole").
END_PROLOG

$prolog->do('hanoi(4)');

Hopefully I'll have something uploaded by this weekend.