SE450: A Linked List: Internal Iterator [3/25] Previous pageContentsNext page

This is an internal iterator.

The iterator controls the traversal.

file:iterator/listthree/Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package iterator.listthree;

/* public */
interface List {
  public void accept(IntIterator i);
}

/* public */
class ListF {
  private ListF() {}
  public static final List nil = new Nil(); /* Singleton */
  public static final List cons(int hd, List tl) /* Factory */ {
    return new Cons(hd, tl);
  }
}

/* public */
interface IntIterator {
  public void run(int element, List rest);
}


/*
 *************************************************************************
 * List classes.
 *************************************************************************
 */
class Nil implements List {
  Nil() {}
  public String toString() { return "nil"; }
  public void accept(IntIterator i) { }
}

class Cons implements List {
  private final int hd;
  private final List tl;
  Cons(int hd, List tl) { this.hd = hd; this.tl = tl; }
  public String toString() { return hd + "::" + tl.toString(); }
  public void accept(IntIterator i) {
    i.run(hd, tl);
  }
}

/*
 *************************************************************************
 * Internal Iterators.
 * Traversal controlled by the iterator.
 *************************************************************************
 */
class Sum implements IntIterator {
  public int value = 0;
  public void run(int hd, List tl) {
    value += hd;
    tl.accept(this);
  }
}

class Reverse implements IntIterator {
  public List value = ListF.nil;
  public void run(int hd, List tl) {
    value = ListF.cons(hd, value);
    tl.accept(this);
  }
}

/*
 *************************************************************************
 * A test case.
 *************************************************************************
 */
public class Main {
  public static void main(String[] args) {
    List test = ListF.cons(1, ListF.cons(2, ListF.cons(3, ListF.nil)));
    System.out.println(test);

    Sum v1 = new Sum();
    test.accept(v1);
    System.out.println(v1.value);

    Reverse v3 = new Reverse();
    test.accept(v3);
    System.out.println(v3.value);
  }
}

Previous pageContentsNext page