/* Author: Jeff Dalton * Updated: Thu Jul 19 04:31:06 2001 by Jeff Dalton * Copyright: (c) 2001, AIAI, University of Edinburgh */ package ix.test; import java.util.*; import ix.util.*; import ix.util.lisp.*; public class SConsTest { public static void main(String[] argv) { LList a = Lisp.list("a", "b", "c"); // PatternCons pattern = (PatternCons)new PatternCons().convert(a); PatternCons pattern = new PatternCons(a); Debug.noteln("PatternCons =", pattern); List l = pattern; LList ll = pattern; Pattern p = pattern; Debug.noteln("List =", l); Debug.noteln("LList =", ll); Debug.noteln("Pattern =", pattern); SCons s1 = new SCons(pattern); s1.addAll(Lisp.list("d", "e", "f")); Debug.noteln("addAll result", s1); Debug.noteln("pattern =", pattern); try { new SCons(new LinkedList()); // try adding empty List } catch(Exception e) { Debug.noteException(e); } finally { Debug.noteln("Should have complained about adding an empty."); } } public static class SCons extends Cons { public SCons(Object car, LList cdr) { super(car, cdr); } public SCons(Collection c) { this(null, Lisp.NIL); Iterator i = c.iterator(); if (!i.hasNext()) throw new IllegalArgumentException ("Trying to add an empty collection to an SCons"); writeIn(this, c.iterator()); } protected SCons newInstance(Object car, LList cdr) { return new SCons(car, cdr); } public boolean addAll(Collection c) { Iterator i = c.iterator(); if (!i.hasNext()) return false; SCons tail = (SCons)this.lastCons(); SCons new_tail = newInstance(null, Lisp.NIL); tail.setCdr(new_tail); writeIn(new_tail, i); return true; } private void writeIn(SCons tail, Iterator i) { Debug.assert(tail.car() == null); tail.setCar(i.next()); while (i.hasNext()) { tail.setCdr(newInstance(i.next(), Lisp.NIL)); tail = (SCons)tail.cdr(); } } } // Given the mechanisms defined above, you can define a new // "Structured Cons" class like this: public static interface Pattern { public Object getVerb(); public List getParameters(); } public static class PatternCons extends SCons implements Pattern { public PatternCons(Object car, LList cdr) { super(car, cdr); } public PatternCons(Collection c) { super(c); } public SCons newInstance(Object car, LList cdr) { return new PatternCons(car, cdr); } public Object getVerb() { return car(); } public List getParameters() { return cdr(); } } }