public static void main(String[] args) { System.out.println("Java is an island in Indonesia."); }
Here is a recursive definition of factorial:
public static int factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n - 1); } }Here is an iterative definition using a for loop:
public static int factorial(int n) { int res = 1; for (int i = 1; i <= n; i++) { res = res * i; } return res; }Both run in linear time, but the recursive definition will be a bit slower and use a bit more memory in Java.
public static void listReverse(ArrayList<Object> p) { for (int i = 0; i < p.size() / 2; i++) { Object pi = p.get(i); p.set(i, p.get(p.size() - i - 1)); p.set(p.size() - i - 1, pi); } }This is similar to the Python procedure from class, but more complex in Java since we cannot swap the elements without introducing a new variable to store the result temporarily.
ArrayList<Object> a = new ArrayList<String>();This produes a compiler error:
Type mismatch: cannot convert from ArrayList<String> to ArrayList<Object>Note that String is a subtype of Object, so it is okay to add a String to an ArrayList<Object>.
public void updateVariable(String name, SVal value) { if (frame.containsKey(name)) { frame.put(name, value); } else if (parent != null) { parent.updateVariable(name, value); } else { throw new EvalError("Undefined name " + name); } }Then, we add an evaluation rule for assignment:
public static void evalAssignment(SExpr expr, Environment env) { assert isAssignment(expr); ArrayListNote that most of the code is for error checking. The essence of the method is just:def = expr.getList(); if (def.size() != 3) { throw new EvalError("Bad assignment: " + expr.toString()); } if (!def.get(1).isAtom()) { throw new EvalError("Bad assignment: name must be a string: " + expr.toString()); } String name = def.get(1).getAtom(); if (!env.hasVariable(name)) { throw new EvalError("Bad assignment: name must be defined: " + expr.toString()); } env.updateVariable(name, meval(def.get(2), env)) }
public static void evalAssignment(SExpr expr, Environment env) { ArrayListBut, we need the code to check that the variable is defined and report an evaluation error when it is not, and to check the structure of the assignment expression is correct.def = expr.getList(); env.updateVariable(def.get(1).getAtom(), meval(def.get(2), env)) }
public static SVal evalBegin(SExpr expr, Environment env) throws EvalError { assert (isBegin(expr)); SVal res = null; for (SExpr s : expr.getList().subList(1, expr.getList().size())) { res = meval(s, env); } return res; }Note that (begin) with no expressions correctly evaluates to null, which represents no value in the interpreter.
You must be logged in to post a comment.