/* * Name: Mike Cifelli * Course: CIS 443 - Programming Languages * Assignment: Lisp Parser */ package parser; /** * This class represents a Lisp CONS cell in the PL-Lisp implementation. */ public class Cons extends SExpression { private SExpression car; private SExpression cdr; /** * Create a new CONS cell with the specified car and cdr. * * @param car * the car of this CONS cell * @param cdr * the cdr of this CONS cell */ public Cons(SExpression car, SExpression cdr) { this.car = car; this.cdr = cdr; } /** * Retrieve the car of this CONS cell. * * @return * the car of this CONS cell */ public SExpression getCar() { return car; } /** * Retrieve the cdr of this CONS cell. * * @return * the cdr of this CONS cell */ public SExpression getCdr() { return cdr; } /** * Set the car of this CONS cell to the specified value. * * @param newCar * the value to assign to the car of this CONS cell */ public void setCar(SExpression newCar) { car = newCar; } /** * Set the cdr of this CONS cell to the specified value. * * @param newCdr * the value to assign to the cdr of this CONS cell */ public void setCdr(SExpression newCdr) { cdr = newCdr; } /** * Test if this S-expression is a CONS cell. * * @return * true */ public boolean consp() { return true; } /** * Returns a string representation of this CONS cell. * * @return * a string representation of this CONS cell */ public String toString() { return ("(" + toStringAux()); } // Returns a string representation of the car of a CONS cell followed by // its cdr. If the cdr of this CONS cell is not a CONS cell itself, this // method places a ')' at the end of its return value. Also, if the cdr of // this CONS cell is NIL, it will not be included in the return value of // this method. When used in conjunction with the 'toString' method of this // class, this method provides a means for creating the correct string // representation of a list. // // Returns: a string representation of the car of a CONS cell followed by // its cdr private String toStringAux() { if (cdr.nullp()) { return (car.toString() + ")"); } else if (cdr.consp()) { return (car.toString() + " " + ((Cons) cdr).toStringAux()); } // the cdr of this CONS cell is not a list return (car.toString() + " . " + cdr.toString() + ")"); } }