/** Our internal representation of a Parity expr * in the T0 language. * See http://www.radford.edu/itec380/2018fall-ibarland/Project * * @author Ian Barland * @version 2018.Nov.16 */ public class Parity extends Expr { static final String START_TOKEN = "even"; static final String STOP_TOKEN = "dawg"; Expr test, evenAns, oddAns; Parity( Expr _test, Expr _evenAns, Expr _oddAns) { this.test = _test; this.evenAns = _evenAns; this.oddAns = _oddAns; } public String toString() { return START_TOKEN+"? " + this.test.toString() + " dope " + this.evenAns.toString() + " nope " + this.oddAns.toString() + " " + STOP_TOKEN ; } public static Parity parse( java.util.Scanner s, String punctuation ) { assert UtilIan.nextSplittingBy(s,punctuation).equals(START_TOKEN); // consume&verify the "even" UtilIan.nextChar(s,'?'); // verify&consume the "?" // NOTE: recur with `Expr.parse` -- not `parse` = `Parity.parse` which is NOT what we want! Expr theTest = Expr.parse(s,punctuation); assert UtilIan.nextSplittingBy(s,punctuation).equals("dope"); Expr theEvenAns = Expr.parse(s,punctuation); assert UtilIan.nextSplittingBy(s,punctuation).equals("nope"); Expr theOddAns = Expr.parse(s,punctuation); assert UtilIan.nextSplittingBy(s,punctuation).equals(STOP_TOKEN); // consume&verify the "dawg" return new Parity(theTest,theEvenAns,theOddAns); } static final double EPSILON = 1e-10; public Value eval() { if ( Math.abs((((Num)(this.test.eval())).doubleValue()) % 2) < EPSILON ) { return this.evenAns.eval(); } else { return this.oddAns.eval(); } } @Override public boolean equals( /* Parity this, */ Object that) { if (this==that) { return true; } else if (that==null) { return false; } else if (this.getClass() != that.getClass()) { return false; } else { Parity thatt = (Parity) that; return this.test.equals(thatt.test) && this.evenAns.equals(thatt.evenAns) && this.oddAns.equals(thatt.oddAns); } } @Override public int hashCode() { if (cachedHash == null) { int hashSoFar = (int)0x3141834e907b1159L; // fingerprint hashSoFar += this.test.hashCode(); hashSoFar *= 31; hashSoFar += this.evenAns.hashCode(); hashSoFar *= 31; hashSoFar += this.oddAns.hashCode(); cachedHash = hashSoFar; } return cachedHash; } private Integer cachedHash = null; }