In Expressions

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 4 11:10:22 PST 2017


On Saturday, 4 March 2017 at 17:11:46 UTC, Andrey wrote:
> Hello, is there any way to using in expression like in python, 
> e.g.
>> if 4 in [1, 3, 4]:
>>     do something
>
> My code in D
>> if (regionAlign in [RegionAlign.top, RegionAlign.bottom]) {
>>    ...
>> }
>
> throws an error:
>> incompatible types for (((cast(Widget)this).regionAlign()) in 
>> ([top, bottom])): 'RegionAlign' and 'RegionAlign[]'

The reason this is disallowed for normal arrays is that finding a 
key in an array is O(n) while finding a key in an associative 
array is O(1). Rather than let users unknowingly write code that 
looks the same but is far slower for arrays, D doesn't allow 
this. You can use std.algorithm.among, however.

import std.algorithm;

if (regionAlign.among!(RegionAlign.top, RegionAlign.bottom))
{
     //etc.
}

http://dlang.org/phobos/std_algorithm_comparison.html#.among


More information about the Digitalmars-d-learn mailing list