typeof(SortedRange) and is operator

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 8 13:14:41 PST 2016


On Tuesday, November 08, 2016 13:22:35 RazvanN via Digitalmars-d-learn 
wrote:
> Sorry, I accidentally posted the above message and I don't know
> how to erase it.
> The following post is the complete one:
>
> Given the following code:
>
> int[] arr = [1, 2, 9, 4, 10, 6];
> auto r    = sort(arr);
>
> if(is(typeof(r) == SortedRange!(int[], "a<b")))
>      writeln("first if");
>
> if(is(typeof(r) == SortedRange!(int[], "a < b")))
>      writeln("second if");
>
> The program outputs only "second if". I assumed that it should
> have printed both
> ifs. Is this a bug?

No, as the others have point out, it's not a bug. If anything it's a
language design flaw that no one has figured out how to resolve yet.

The big thing here is that lambdas in general are not comparable, even if
they are _exactly_ the same. e.g. this will fail to compile

int[] arr;
auto r1 = sort!((a, b) => a < b)(arr);
auto r2 = sort!((a, b) => a < b)(arr);
static assert(typeof(r1) == typeof(r2));

You get an error like

Error: static assert  (is(SortedRange!(int[], __lambda1) == SortedRange!
(int[], __lambda2))) is false

It doesn't think that __lambda1 and __lambda2 are the same, and that's with
two totally identical lambdas. The language and the compiler simply
do not have a way to do a comparison of lambdas. It's probably possible to
make them do it, but no one has figured out how to do it yet.

String lambdas predate the lambda syntax that I used above, and they have
largely been replaced by that new syntax. But string lambdas are still in
use in part because it's possible to compare strings for equality, and
therefore it's possible to compare string lambdas for equality. But even
then, it's comparing strings for exact equality and not attempting to
decipher the strings. Part of that is because string lambdas are actually
using a library construct - std.functional.binaryFun in this case - in order
to work, so the language is just comparing two instances of the same
instantiation of a template for equality - e.g. binaryFun!"a < b" and
binaryFun!"a < b", which would be equal, or binaryFun!"a < b" and
binaryFun!"a<b", which would not be. But even if string lambdas were built
into the language as opposed to just being part of the standard library,
we'd just be back to the problem that we have with comparing lambdas in
general.

We'd very much like to see a solution to this problem implemented, but for
now at least, it's just one of those annoyances that you have to deal with.
And if you want two template instantiations with lambdas to be compatible,
you either have to use string lambdas where the strings are identical, or
you have to use an actual function rather than a lambda so that you can pass
the same function to both template instantiations.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list