If
A in [x, y, z]
is considered a valid solution then the function
in(A, x, y, z)
should be considered a valid solution too, especially for a language that allow operator overloading so that cmp(A, x, y, z) could be mapped to
A in x y z
Discussions so far have dwelt on
if (A == x or y or z).
What about the case of
if (A == x and y and z).
Therefore, we would use varargs, a feature found in c, c++, c# and java5.
Let's use java to illustrate.
boolean or(String lhs, String... rhs){
for(String z: rhs){
if (lhs.equals(z) return true;
}
return false;
}
boolean and(String lhs, String... rhs){
for(String z: rhs){
if (!lhs.equals(z) return false;
}
return true;
}
Varargs allow you to define a single function that takes in a variable number of arguments so that you could use the same method to compare
or (A, x)
or (A, x, y)
or (A, x, y, z)
However, the above is defined only for String comparisons, so that we would have to create a pair of methods for each arg type. But then in Java 5 there is generics.
<T extends Comparable<T>>boolean or(T lhs, T... rhs){
for(T z: rhs){
if (lhs.compareTo(z)==0) return true;
}
return false;
}
<T extends Comparable<T>>boolean and(T lhs, T... rhs){
for(T z: rhs){
if (lhs.compareTo(z)!=0) return false;
}
return true;
}
So now you can do comparisons for any type that implements comparable interface.
and(stringA, stringx, stringy)
or(dateA, datex)
Too bad, Java does not allow operator overloading so that we could do
stringA && stringx, stringy
dateA || datex, datey, datez
In c++, I have never attempted operator overloading with varargs to even know if it is possible.
Revisit:
However, revisiting this hours later,
We could define a class
public class <T extends Comparable<T>> Comparigator{
public Comparigator(T lhs){
this.lhs = lhs;
}
final private T lhs;
static public <T extends Comparable<T>> Comparigator is(T lhs){
return (T)new Comparigator(lhs);
}
public boolean inAny(T... rhs){
for(T z: rhs){
if (this.lhs.compareTo(z)==0) return true;
}
return false;
}
public boolean inAll(T... rhs){
for(T z: rhs){
if (this.lhs.compareTo(z)!=0) return false;
}
return true;
}
public boolean gtAny(T... rhs){
for(T z: rhs){
if (this.lhs.compareTo(z)>0) return true;
}
return false;
}
public boolean gtAll(T... rhs){
for(T z: rhs){
if (this.lhs.compareTo(z)<=0) return false;
}
return true;
}
}
Now, we don't need operator overloading at all and we can do
import Comparigator;
.....
is(A).inAny(x,y,z); // or
is(A).inAll(w,x,y,z); // and
is(B).gtAny(k,l,m);
is(C).gtAll(j,k);
And we could expand it and we could do inany, inall, gtany, gtall, ltany, ltall, etc by expanding the comparison functionality.