Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality operator in favour of std.range.equal

I'm curious to why D developers promote use of std.range.equal in cases such as

bool isPalindrome(Range)(in Range range) if 
(isBidirectionalRange!Range)
{
    return range.retro.equal(range);
}

Why isn't equality operator == used here instead?

See also: http://forum.dlang.org/thread/[email protected]#post-qdamjxisavsizvrdpecf:40forum.dlang.org

like image 392
Nordlöw Avatar asked Feb 18 '14 09:02

Nordlöw


1 Answers

The equality operator is for comparing objects of the same type, whereas ranges frequently have drastically different types.

auto result = range1.equal(range2);

will compare the two input ranges regardless of what types they are as long as their elements may be compared, whereas

auto result = range1 == range2;

would require that the two ranges be of the same type, which is rarely the case. At present, there are even many cases where two ranges which should be considered the same type aren't, because the language is unable to compare lambda functions to see whether they're the same function (a serious downside to moving away from string lambdas as we have been, since strings can be compared for equality). Hopefully, this will be remedied in the future, but it does often make comparing ranges with == difficult even if you wanted to.

Also, == is not among the set of operations supported by the range API. range1 == range2 will compile if the two ranges are of the same type (since == is defined for all types), but they could be comparing reference equality or be doing a deeper comparison. It would depend entirely on the range's implementation. All that's required of input ranges is that this code compile:

{
    R r = void;       // can define a range object
    if (r.empty) {}   // can test for empty
    r.popFront();     // can invoke popFront()
    auto h = r.front; // can get the front of the range
}

where R is the range type. No other requirements are put on input ranges. So, you can't rely on == working for them, whereas equal uses the input range API to do its comparison and thus will work with all input ranges with elements which can be compared.

like image 58
Jonathan M Davis Avatar answered Oct 13 '22 09:10

Jonathan M Davis