recursive equal, and firstDifference functions

Jonathan M Davis jmdavisProg at gmx.com
Tue Mar 19 12:40:03 PDT 2013


On Tuesday, March 19, 2013 19:13:14 timotheecour wrote:
> > And how do you even have the concept of recursion without some
> > sort of range or container to recursively iterate through?
> 
> It's not hard: I've done it for a serialization library I've been
> working on (which has some advantages over std.orange, such as
> serializing to json/binary etc. more on this later), as well as
> for my toStringRecurse: it works on any data type roughly as
> follows:
> 
> auto equalRecurse(T)(T a) {
> static if isAssociativeArray!(T)) {
> }
> else static if(isArray!(T)) {
> }
> else static if(is(T == struct) ){
> foreach(i, member; a.tupleof) {
> ...
> }
> else static if...
> }
> 
> >> Expecting the compiler to automagically figure out how to
> >> compare two types for you is just begging for trouble
> 
> I beg to differ. I like to be as lazy as possible when writing
> user code (as opposed to library code). The compiler can do a lot
> of stuff automagically in D thanks to CT reflection. I didn't run
> into problems when using the serialization on rather complex
> nested objects.

Serialization is completely different from comparing the equality of two 
objects. That's opEquals' job. It deals with recursive comparisons like you're 
describing here just fine. There's no reason to define that externallly to the 
type. equal's job, on the other hand, is to compare the elements of two ranges 
- _not_ the ranges themselves - which is fundamentally different from ==.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list