O(1) dictionaries

mandel oh at no.es
Wed Nov 14 04:31:01 PST 2007


Tim Keating Wrote:

> mandel wrote:
> > Hi,
> > 
> > I have made a dictionary that way:
> > enum Word { Hello, Bye };
> > char[][Word] dict;
> > 
> > static this()
> > {
> >    dict = [
> >      Word.Hello : "Hello",
> >      Word.Bye : "Bye"
> >    ];
> > }
> > 
> > Now there are two problems I have with this:
> > 
> > - the dict is an AA, but an array would be much faster,
> >   but it is not possible to assign it via an array literal
> >   with a mixed order and supplied keys.
> > char[][Word.max] dict = [Word.Hello : "Hello", ...]
> 
> Why does the array literal have to be in mixed order? You can just do 
> the enum and the array in the same order:
> 
> enum Word { Hello, Bye };
> char[] dict = [ "Hello", "Bye" ];
> 
> The only complication there is that for a dictionary of any meaningful 
> length, it won't line up quite as nicely. Ensuring each enum value 
> matches its correct word will be a real pain. In this situation, I might 
> use code generation.
You named the reason, it won't line up.
The dict may also change order when words are added and quite possibly regrouped.
The entire alignment will be hard to maintain.

> 
> > - in place initialisation with a literal is not possible.
> >   Instead, the use of "static this" makes the code look long winded.
> 
> It seems from what you say above that you already know its, but that's 
> not true anymore. Array literals were recently added to the language 
> (see the "expressions" section of the language spec).
>From the specs I see that I should have said that statically initialization
is not possible with AAs. The use of "static this" for this causes the binary to abort execution immediately because of "cyclic dependencies" (In cases of multiple static this in different modules).
And a custom init function also doesn't look that nice.

> 
> However, if you think _that's_ long-winded, consider how you would do 
> that initialization in C++ . . .
I know...
But imho it could be done even better in D. :P




More information about the Digitalmars-d mailing list