How about a Hash template?
KennyTM~
kennytm at gmail.com
Fri Apr 29 12:44:37 PDT 2011
On Apr 30, 11 03:12, Andrei Alexandrescu wrote:
> On 4/29/11 8:50 AM, Denis Koroskin wrote:
>> On Thu, 28 Apr 2011 03:10:15 +0400, Andrej Mitrovic
>> <andrej.mitrovich at gmail.com> wrote:
>>
>>> I often see code written like this:
>>>
>>> if (value == somevalue ||
>>> value == someothervalue ||
>>> value == yetanothervalue);
>>>
>>> You could use the switch statement. But that introduces indentation,
>>> and is rarely used for a couple of values.
>>>
>>> I really like the "in" keyword, and I also like hashes since they can
>>> potentially speed up look-ups compared to conventional arrays. So I
>>> thought it would be cool to have a Hash template that constructs an
>>> associative array which you can use especially in if statements when
>>> you just want to know if a runtime value matches some predetermined
>>> value.
>>>
>>> Here's my attempt at writing it:
>>> http://codepad.org/c4sYDSyR
>>>
>>> Whaddya think?
>>
>> Try this:
> [snip]
>
> Nice work. I think this code could earn a place in Phobos:
>
> auto either(Keys...)(Keys keys)
> {
> static struct Result
> {
> bool opIn_r(Key)(Key key)
> {
> foreach (k; keys) {
> if (k == key) {
> return true;
> }
> }
> return false;
> }
> private Keys keys;
> }
> return Result(keys);
> }
>
>
> Andrei
>
This is generally 2~3 times slower than a compile-time solution if the
keys are known in advance (and the former is 1~2 times slower than using
x == y || x == z || ... directly)
(Why do you still use opIn_r? ;) )
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: x.d
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20110430/a3458fe4/attachment.ksh>
More information about the Digitalmars-d
mailing list