Dual conditions in D and Python

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 21 12:44:44 PDT 2015


On Thursday, 21 May 2015 at 19:05:16 UTC, Steven Schveighoffer 
wrote:
> 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

All we need is user-defined opIs and then we're really cooking 
with gas.

if (5 is between(4, 6))
{
     //...
}



More information about the Digitalmars-d-learn mailing list