/* Class representing elements of form (a . b) in D in Jones, Chapter 2 Written by: Kim Bruce, 9/16/2002 */ public class Composite implements D{ private D head; // composite represents (head . tail) private D tail; // Create new composite with "head" as new head and "tail" as new tail // I.e., new element is (head . tail) public Composite(D head, D tail) { this.head = head; this.tail = tail; } // create new list with other as head and this as tail public D cons(D other) { return new Composite(other,this); } // return head of this public D hd(){ return head; } // return tail of this public D tl(){ return tail; } // returns whether argument is nil private boolean isNil(D elt) { return elt == D.nil; } // return true iff this equals other public boolean booleq(D other) { if (other instanceof Composite) { Composite oc = (Composite)other; D otherhead = oc.head; D othertail = oc.tail; return (head.booleq(otherhead) && tail.booleq(othertail)); } else { return false; } } // return dTrue if this equals other and dFalse otherwise public D eq(D other){ if (booleq(other)) return D.dTrue; else return D.dFalse; } // return string representation of composite public String toString() { return "( " + head +" . "+tail+")"; } public boolean isList() { return (head instanceof Atom) && tail.isList(); } public String asList() { if (isList()){ String val = "( "+head; D curTail = tail; while (!isNil(curTail)) { val = val + ", "+curTail.hd(); curTail = curTail.tl(); } return val+" )"; } else { return "error: not a list"; } } }