| 1 |
package test0016; |
| 2 |
|
| 3 |
class Seq<E> { |
| 4 |
E head; |
| 5 |
Seq<E> tail; |
| 6 |
Seq() { |
| 7 |
this(null, null); |
| 8 |
} |
| 9 |
boolean isEmpty() { |
| 10 |
return this.tail == null; |
| 11 |
} |
| 12 |
Seq(E head, Seq<E> tail) { |
| 13 |
this.head = head; |
| 14 |
this.tail = tail; |
| 15 |
} |
| 16 |
<T> Seq<Pair<E,T>> zip(Seq<T> that) { |
| 17 |
if (this.isEmpty() || that.isEmpty()) |
| 18 |
return new Seq<Pair<E,T>>(); |
| 19 |
else |
| 20 |
return new Seq<Pair<E,T>>( |
| 21 |
new Pair<E,T>(this.head, that.head), |
| 22 |
this.tail.zip(that.tail)); |
| 23 |
} |
| 24 |
@Override |
| 25 |
public String toString() { |
| 26 |
StringBuffer buffer = new StringBuffer(); |
| 27 |
if (head != null) { |
| 28 |
buffer.append(head); |
| 29 |
} |
| 30 |
if (tail != null) { |
| 31 |
buffer.append(tail); |
| 32 |
} |
| 33 |
return String.valueOf(buffer); |
| 34 |
} |
| 35 |
public class Zipper<T> { |
| 36 |
Seq<Pair<E,T>> zip(Seq<T> that) { |
| 37 |
if (Seq.this.isEmpty() || that.isEmpty()) |
| 38 |
return new Seq<Pair<E,T>>(); |
| 39 |
else |
| 40 |
return new Seq<Pair<E,T>>( |
| 41 |
new Pair<E,T>(Seq.this.head, that.head), |
| 42 |
Seq.this.tail.zip(that.tail)); |
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
class Pair<A, B> { |
| 47 |
A fst; |
| 48 |
B snd; |
| 49 |
|
| 50 |
Pair(A a, B b) { |
| 51 |
this.fst = a; |
| 52 |
this.snd = b; |
| 53 |
} |
| 54 |
@Override |
| 55 |
public String toString() { |
| 56 |
StringBuffer buffer = new StringBuffer(); |
| 57 |
buffer.append("("); |
| 58 |
buffer.append(fst); |
| 59 |
buffer.append(", "); |
| 60 |
buffer.append(snd); |
| 61 |
buffer.append(")"); |
| 62 |
return String.valueOf(buffer); |
| 63 |
} |
| 64 |
@Override |
| 65 |
public boolean equals(Object other) { |
| 66 |
return other instanceof Pair && |
| 67 |
equals(fst, ((Pair)other).fst) && |
| 68 |
equals(snd, ((Pair)other).snd); |
| 69 |
} |
| 70 |
private boolean equals(Object x, Object y) { |
| 71 |
return x == null && y == null || x != null && x.equals(y); |
| 72 |
} |
| 73 |
} |
| 74 |
public class X { |
| 75 |
public static void main(String[] args) { |
| 76 |
Seq<String> strs = new Seq<String>("a", new Seq<String>("b", new Seq<String>())); |
| 77 |
Seq<Number> nums = new Seq<Number>(new Integer(1), new Seq<Number>(new Double(1.5), new Seq<Number>())); |
| 78 |
Seq<String>.Zipper<Number> zipper = strs.new Zipper<Number>(); |
| 79 |
Seq<Pair<String,Number>> combined = zipper.zip(nums); |
| 80 |
System.out.println(combined); |
| 81 |
} |
| 82 |
} |