Associative arrays with void values

dsimcha dsimcha at yahoo.com
Sun Apr 12 15:52:24 PDT 2009


== Quote from Doctor J (nobody at nowhere.com)'s article
> Sometimes you want to use an associative array just to track keys you've seen,
or count distinct keys, and you don't care about the values.  The language will
let you declare an array such as void[int]; but you can't actually do anything
with it:
> void main()
> {
>     void[int] voidmap;    // This compiles
>     voidmap[1] = void;  // This doesn't
> }
> My question is, is this a common or useful enough special case to warrant
inclusion in the language?  Or should I just go quietly and use a bool or a byte
or something?


IMHO using AAs as makeshift sets is a terrible solution for a few reasons:

1.  Without the void[someType] hack, it wastes at least one byte per element,
sometimes a lot more depending on alignment issues.  If you use the void[SomeType]
hack, you get really screwy syntax, to the point where a library type would have
much better syntax.  This means you gain nothing except maybe usability at compile
time by having it builtin.
2.  A proper set type needs to have some extra methods like intersect, etc.  If
we're going to add all this, we should step back and figure out how to add sets to
the language the right way instead of doing it the most immediately expedient way
and being stuck with it.
3.  D's current AA implementation kind of sucks anyhow, at least when it interacts
with conservative GC.  You probably don't want to build too much more stuff on top
of it.

That said, sets should be in either the language or in the standard lib.  There
are at least a few good implementations (Tango, Dcollections, probably a bunch
more out there). Including one with an appropriate license and maybe some
consistency tweaks in Phobos wouldn't be too hard technically, though it might be
politically.

On the other hand, I'm not sure if it makes sense from a consistency perspective
to have AAs as a builtin, first class type and sets as a library type.  I'm not
sure whether this argues more for AAs being a library type or sets being builtin,
but the inconsistency is just weird.



More information about the Digitalmars-d mailing list