recursive equal, and firstDifference functions
John Colvin
john.loughran.colvin at gmail.com
Tue Mar 19 11:49:45 PDT 2013
On Tuesday, 19 March 2013 at 08:25:45 UTC, timotheecour wrote:
> we need a std.algorithm.equalRecurse(T1,T2)(T1 a, T2 b) that
> compares recursively a and b;
>
> its behavior should be:
>
> if opEqual is defined, call it
The problem is, Object defines opEqual as "bool opEquals(Object
o){return this is o;}", so that ruins a lot of class comparisons.
An example implementation of what I think you're getting at:
http://dpaste.dzfl.pl/a7889060
bool deep_equal(T)(T a, T b) {
static if(isInputRange!T)
return rec_equal(a, b);
else static if(__traits(isScalar, T) /*|| __traits(hasMember, T,
"opEquals")*/)
return a == b;
else {
foreach(i, a_field; a.tupleof)
if(!deep_equal(a_field, b.tupleof[i]))
return false;
return true;
}
}
bool rec_equal(size_t max_depth = size_t.max, R0, R1)(R0 r0, R1
r1)
if(NumDims!R0 == NumDims!R1)
{
static if(NumDims!R0 == 0 || max_depth == 0)
return r0 == r1;
else {
mixin("return " ~
replicate("equal!", min(max_depth-1, NumDims!(R0)-1)) ~
"equal(r0, r1);"
);
}
}
template NumDims (T) {
static if(is(ElementType!T == void))
const NumDims = 0;
else
const NumDims = 1 + NumDims!(ElementType!T);
}
More information about the Digitalmars-d-learn
mailing list