1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 package com.generationjava.util;
33
34 /***
35 * A Lisp like Pair object.
36 */
37 public class Pair {
38
39 /***
40 * Create a String version of a tree of pairs.
41 */
42 public String dumpTree() {
43 return dumpTree(this);
44 }
45 /***
46 * Create a String version of a tree of pairs using this start pair.
47 */
48 public String dumpTree(Pair pair) {
49 String str = "";
50 boolean ret = false;
51 if(! (pair.car() instanceof Pair) ) {
52 str += pair.car();
53 }
54 if(! (pair.cdr() instanceof Pair) ) {
55 str += pair.cdr();
56 }
57 if(pair.car() instanceof Pair) {
58 str += dumpTree( (Pair)pair.car()); ret = true;
59 }
60 if(pair.cdr() instanceof Pair) {
61 str += dumpTree( (Pair)pair.cdr()); ret = true;
62 }
63 if(ret) str += "\n";
64 return str;
65 }
66
67 private Object one;
68 private Object two;
69 private int weighting1;
70 private int weighting2;
71
72 /***
73 * Create a Pair with two Pairs in it.
74 */
75 public Pair(Pair one, Pair two) {
76 this(one, two, one.weighting(), two.weighting() );
77 if(one.cdr() == null) {
78 this.one = one.car();
79 }
80 if(two.cdr() == null) {
81 this.two = two.car();
82 }
83 }
84
85 /***
86 * A Pair with two Objects, weighted with the weightings given.
87 */
88 public Pair(Object one, Object two, int weighting1, int weighting2) {
89 this.one = one;
90 this.two = two;
91 this.weighting1 = weighting1;
92 this.weighting2 = weighting2;
93 }
94 /***
95 * A Pair with two Objects of equal weighting.
96 */
97 public Pair(Object one, Object two) {
98 this(one, two, 1, 1);
99 }
100
101 /***
102 * A Pair with only one object of a specific weighting.
103 */
104 public Pair(Object one, int weighting) {
105 this(one, null, weighting, 0);
106 }
107 /***
108 * A Pair with only one object.
109 */
110 public Pair(Object one) {
111 this(one, null, 1, 0);
112 }
113
114 /***
115 * Get the combined weighting of this Pair.
116 */
117 public int weighting() {
118 return carWeighting() + cdrWeighting();
119 }
120
121 /***
122 * Get the weighting of the first element of this Pair.
123 */
124 public int carWeighting() {
125 if( one instanceof Pair ) {
126 return ( (Pair)one ).weighting();
127 } else {
128 return weighting1;
129 }
130 }
131
132 /***
133 * Get the weighting of the second element of this Pair.
134 */
135 public int cdrWeighting() {
136 if( two instanceof Pair ) {
137 return ( (Pair)two ).weighting();
138 } else {
139 return weighting2;
140 }
141 }
142
143 /***
144 * Get the first element of this Pair.
145 */
146 public Object car() {
147 return one;
148 }
149
150 /***
151 * Get the second element of this Pair.
152 */
153 public Object cdr() {
154 return two;
155 }
156
157 /***
158 * Simple debug version of this Pair.
159 */
160 public String toString() {
161 return "{"+one+"["+weighting1+"]:"+two+"["+weighting2+"]}";
162 }
163 }