Dual conditions in D and Python

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 21 10:43:14 PDT 2015


On Thursday, May 21, 2015 16:57:14 Dennis Ritchie via Digitalmars-d-learn wrote:
> Hi,
> In Python I can write this:
>
> if (4 <= 5 <= 6):
>      print ("OK")
> -----
> http://rextester.com/NNAM70713
>
> In D, I can only write this:
>
> import std.stdio;
>
> void main() {
>
>      if (4 <= 5 && 5 <= 6)
>          puts("OK");
> }
> -----
> http://rextester.com/FICP83173
>
> I wanted to ask what is the reason? Maybe the program on Python's
> slower because of this? Or legacy C/C++ affected D?

No C-based language allows what python does, and based on operators work in
C-based languages, what python is doing simply doesn't fit or make sense.
What happens in C/C++/D/Java/C#/etc. land is that 4 <= 5 results in a bool,
at which point you'd end up with a comparison between that bool and 6, which
is _not_ something that you want. But with other operators _is_ very much
what you'd want. Operator chaining works in the same way across all
operators in C-based languages, and trying to make 4 <= 5 <= 6 be equivalent
to 4 <= 5 && 5 <= 6 would make it so that they weren't consistent. And it
wouldn't make the language any more powerful, because you can quite easily
just do 4 <= 5 && 5 <= 6 instead of 4 <= 5 <= 6. It only costs you a few
characters and results in the language being far more consistent. I'm
honestly quite surprised that python would allow such a thing, but they seem
to do a lot of stuff that most programmers from C-based languages
(especially C++) would think is crazy.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list