Trivial Prolog in Java

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