Trivial Prolog in Java

01: package ca.draisey.free.tprolog;
02:
03:
04:
05:
06:
07: // pairs are the right-to-left "list constructors" of formal functions and predicates
08: final class PairTerm extends Term {
09:         PairTerm( final Term l, final Term r )
10:         {
11:                 left = l; right = r;
12:         }
13:
14:         // for pretty output
15:         final void listing( final int f, final Variables these, final java.io.PrintWriter p, final Monitor m )
16:         {
17:                 //System.out.print("p");
18:                 m.monitor();
19:                 if( ( f & -2 ) == 0 ) {
20:                         p.print( "PairTerm( " );
21:                         left.listing( f, these, p, m );
22:                         p.print( ", " );
23:                         right.listing( f, these, p, m );
24:                         p.print( ")" );
25:                 }
26:                 else {
27:                         left.listing( f, these, p, m );
28:                         p.print( "( " );
29:                         right.listing( f, these, p, m );
30:                         p.print( " )" );
31:                 }
32:         }
33:
34:         // a helper function for indexing the database -- pass this to the left
35:         final String getkey() {
36:                 return left.getkey() + "()";
37:         }
38:
39:         // unifythrough -- by juggling terms unifythrough does dynamic dispatch on its Term argument --
40:         protected final void unifythrough( final Term that, final Variables these, final Variables those, final Successor success )
41:         {
42:                 that.unifytoPair( this, those, these, success );
43:         }
44:
45:         // the meat of class PairTerm
46:         protected final void unifytoPair( final PairTerm that, final Variables these, final Variables those, final Successor success )
47:         {
48:                 //System.out.print("P");
49:                 left.unifythrough( that.left, these, those, success.succession().new SuccessionSuccessor() {
50:                         void succeed()
51:                         {
52:                                 right.unifythrough( that.right, these, those, success );
53:                                 // note -- closure on private fields hadn't used to work in Java
54:                         }
55:                 } );
56:         }
57:         // unifytoAtom fails by default
58:         // all terms inherit the ability to bind an unbound variable from Term -- always succeeds --
59:
60:         // the PairTerm node structure
61:         private final Term left, right;
62: }
63:
64: // fin