Dual conditions in D and Python

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 21 12:05:16 PDT 2015


On 5/21/15 12:57 PM, Dennis Ritchie 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?


There is this possibility:

switch(5){
    case 4: .. case 6:
}

You could also make some nifty abuse-of-syntax types:

struct Between(T)
{
    T low;
    T high;
    bool opBinaryRight!(op : "in")(T val) { return val >= low && val <= 
high;}
}

auto between(T)(T low, T high) { return Between!T(low, high); }

if(5 in between(4, 6))

:)

-Steve


More information about the Digitalmars-d-learn mailing list