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
package iterator.listtwo;

/* 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 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.accept(i);
  }
}

/*
 *************************************************************************
 * Internal Iterators.
 * Traversal controlled by the list.
 *************************************************************************
 */
class Sum implements IntIterator {
  public int value = 0;
  public void run(int hd) {
    value += hd;
  }
}

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

/*
 *************************************************************************
 * 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);
  }
}