/** * A class containing a main program for testing out the evaluator. */ public class FactorialTest { /** * When this program is run, it does the equivalent of the * following ML program:
     * fun f n = if n = 0 then 1 else f(n-1)*n;
     * val five = 6-1;
     * f five;
     * 
*/ public static void main(String[] args) { Expression fBody = getBody(); // messy details are in getBody() Expression sixMinusOne = new Application(new Application(new Variable("-"), new Constant(6)), new Constant(1)); Expression fFive = new Application(new Variable("f"), new Variable("five")); Environment env0 = new InitialEnvironment(); Environment env1 = new ActivationRecord("f", "n", fBody, env0); Environment env2 = new ActivationRecord("five", sixMinusOne.eval(env1), env1); System.out.println(fFive.eval(env2)); } private static Expression getBody(){ // This produces the body of the function f, // if n = 0 then 1 else f(n-1)*n; // this expresion is complex enough that it seems worth // building up one step at a time. Expression n = new Variable("n"); Expression one = new Constant(1); Expression zero = new Constant(0); Expression times = new Variable("*"); Expression minus = new Variable("-"); Expression equals = new Variable("="); Expression f = new Variable("f"); Expression nMinusOne = new Application(new Application(minus, n), one); Expression fNMinusOne = new Application(f, nMinusOne); Expression product = new Application(new Application(times, fNMinusOne), n); Expression nEqualsZero = new Application(new Application(equals, n), zero); return new Conditional(nEqualsZero, one, product); } }