001package iterator.listone; 002import java.util.NoSuchElementException; 003 004/* public */ 005interface List { 006 public Iterator newIterator(); 007} 008 009/* public */ 010class ListF { 011 private ListF() {} 012 public static final List nil = new Nil(); /* Singleton */ 013 public static final List cons(int hd, List tl) /* Factory */ { 014 return new Cons(hd, tl); 015 } 016} 017 018/* public */ 019interface Iterator { 020 public boolean hasNext(); 021 public int next(); 022} 023 024/* 025 ************************************************************************* 026 * List classes. 027 ************************************************************************* 028 */ 029class Nil implements List { 030 Nil() {} 031 public String toString() { return "nil"; } 032 public Iterator newIterator() { return new NullIterator(); } 033} 034 035class Cons implements List { 036 final int hd; 037 final List tl; 038 Cons(int hd, List tl) { this.hd = hd; this.tl = tl; } 039 public String toString() { return hd + "::" + tl.toString(); } 040 public Iterator newIterator() { return new ListIterator(this); } 041} 042 043class NullIterator implements Iterator { 044 NullIterator() { } 045 public boolean hasNext() { return false; } 046 public int next() { throw new NoSuchElementException(); } 047} 048 049class ListIterator implements Iterator { 050 private List node; 051 ListIterator(List node) { this.node = node; } 052 public boolean hasNext() { 053 return node != ListF.nil; 054 } 055 public int next() { 056 if (! hasNext()) 057 throw new NoSuchElementException(); 058 int result = ((Cons)node).hd; 059 node = ((Cons)node).tl; 060 return result; 061 } 062} 063 064/* 065 ************************************************************************* 066 * A test case. 067 ************************************************************************* 068 */ 069public class Main { 070 public static void main(String[] args) { 071 List test = ListF.cons(1, ListF.cons(2, ListF.cons(3, ListF.nil))); 072 System.out.println(test); 073 074 int sum=0; 075 for (Iterator i = test.newIterator(); i.hasNext(); ) 076 sum += i.next(); 077 System.out.println(sum); 078 079 List rev=ListF.nil; 080 for (Iterator i = test.newIterator(); i.hasNext(); ) 081 rev = ListF.cons(i.next(),rev); 082 System.out.println(rev); 083 } 084}