between and among: worth Phobosization?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Dec 16 15:04:09 PST 2013


On 12/16/13 2:55 PM, "Ola Fosheim Grøstad" 
<ola.fosheim.grostad+dlang at gmail.com>" wrote:
> On Monday, 16 December 2013 at 21:45:40 UTC, Walter Bright wrote:
>>> uint among(T, Us...)(T v, Us vals)
>>> {
>>>     foreach (i, U; Us)
>>>     {
>>>         if (v == vals[i]) return i + 1;
>>>     }
>>>     return 0;
>>> }
>>
>> This has O(n) behavior, which might be unexpected for the user.
>
> I would expect one table-lookup for this if vals contains strings, not N
> ifs. If you look at the example, most of them could be done with perfect
> hashing on a single character.
>
> Is it possible for the compiler/template system to turn this into a
> switch/dictionary? Or is there something in the language/compiler that
> makes that impossible?

It's a good idea, but unfortunately we don't have partial evaluation. 
We'd need to move whatever compile-time work is to be done in the 
template arguments area, i.e.

value.among!("foo", "bar", "baz")

as opposed to

value.among("foo", "bar", "baz")

Now that I think of it we can easily support both forms.



Andrei



More information about the Digitalmars-d mailing list