14 ///--------------------------------------------------------------------------
17 var prog = os.Args[0];
19 func bail(msg string) {
20 fmt.Fprintf(os.Stderr, "%s: %s\n", prog, msg);
24 ///--------------------------------------------------------------------------
25 /// Iteration protocol.
27 /// A data type implements the iteration protocol by providing a method which
28 /// simply writes its consistuent elements to a provided channel. The
29 /// iteration machinery runs this method in a separate goroutine.
31 // A convenient abbreviation.
34 type Iterable interface {
35 // Simply put the items to the channel CH one at a time.
36 Iterate(ch chan<- any);
40 type Iterator <-chan any;
42 // Returns an iterator for a given iterable thing.
43 func MakeIterator(it Iterable) Iterator {
52 // Returns the next item from an iterator IT. If there is indeed an item
53 // available, return it and true; otherwise return nil and false.
54 func (it Iterator) Next() (any, bool) {
59 // Answer whether the iterators return the same items in the same order.
60 // Equality is determined using `=='. Maybe we'll do better some day.
61 func SameIterators(ia, ib Iterator) bool {
63 a, any_a := ia.Next();
64 b, any_b := ib.Next();
65 if !any_a { return !any_b }
71 ///--------------------------------------------------------------------------
74 // Just a simple binary tree.
80 // Iteration is easy. Note that recursion is fine here: this is just a
82 func (n *Node) Iterate(ch chan<- any) {
83 if n == nil { return }
89 // Parse a tree from a textual description. The syntax is simple:
91 // tree ::= empty | `(' tree char tree `)'
93 // where the ambiguity is resolved by declaring that a `(' is a tree if we're
95 func ParseTree(s string) *Node {
96 var parse func(int) (*Node, int);
99 parse = func(i int) (*Node, int) {
100 if i < n && s[i] == '(' {
101 left, i := parse(i + 1);
102 if i >= n { bail("no data") }
104 right, i := parse(i + 1);
105 if i >= n || s[i] != ')' { bail("missing )") }
106 return &Node { data, left, right }, i + 1;
111 if i < n { bail("trailing junk") }
115 ///--------------------------------------------------------------------------
119 switch len(os.Args) {
121 t := ParseTree(os.Args[1]);
122 i := MakeIterator(t);
124 item, winp := i.Next();
126 fmt.Printf("%c", item);
130 ia := MakeIterator(ParseTree(os.Args[1]));
131 ib := MakeIterator(ParseTree(os.Args[2]));
132 if SameIterators(ia, ib) {
133 io.WriteString(os.Stdout, "match\n");
135 io.WriteString(os.Stdout, "no match\n");
142 ///----- That's all, folks --------------------------------------------------