[Issue 7878] New: A problem with purity and general templated algorithms

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Apr 9 10:53:37 PDT 2012


http://d.puremagic.com/issues/show_bug.cgi?id=7878

           Summary: A problem with purity and general templated algorithms
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: bearophile_hugs at eml.cc


--- Comment #0 from bearophile_hugs at eml.cc 2012-04-09 10:54:17 PDT ---
This is a spinoff of the closed Issue 7864 , see there for more info.

This is not a bug report and it's not even a real enhancement request, it's
just a note to not forget a small but what I think real problem in D+Phobos. At
the moment I don't have suggestions to how improve the situation. Ideas are
welcome.


This is wrong D2 code:


class C {
    string str;

    this(string str_) {
        this.str = str_;
    }

    override int opCmp(Object o) const {
        import std.string;
        auto rhs = cast(C)o;
        assert(rhs);
        return cmp(str, rhs.str);
    }
}

struct S {
    C c;

    int opCmp()(const auto ref S rhs) const pure {
        if (c < rhs.c) return -1;
        if (c > rhs.c) return 1;
        return 0;
    }
}

void main() {
    import std.algorithm;
    S[] stuff;
    sort(stuff);
}



DMD 2.059beta4 gives:

...\dmd2\src\phobos\std\algorithm.d(6802): Error: static assert  "Invalid
predicate passed to sort: a < b"
test.d(29):        instantiated from here: sort!("a <
b",cast(SwapStrategy)0,S[])


The error message looks correct, but it's really too much general, it doesn't
give enough information to the 
programmer, that is left to guess why the code doesn't work. This is quite bad.


To fix this program the first opCmp too must be pure:

    override int opCmp(Object o) const pure {

But in a little more complex program it risks being not easy to find such bugs.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list