Enumap -- a lightweight AA alternative when your keys are enums

rcorre via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Thu Sep 10 19:17:23 PDT 2015


I frequently find myself needing a data structure that maps each 
member of an enum to a value;
something similar what Java calls an EnumMap 
(http://docs.oracle.com/javase/7/docs/api/java/util/EnumMap.html).

I couldn't find any D implementation out there, so I wrote a 
little module for it.
Enumap is available on Github (https://github.com/rcorre/enumap)
and via dub (http://code.dlang.org/packages/enumap).
Docs are hosted at http://rcorre.github.io/enumap/.

An Enumap is basically a thin wrapper that makes a static array 
look like an associative array:

---
enum Attribute {
  strength, dexterity, constitution, wisdom, intellect, charisma
}

Enumap!(Attribute,int) attributes;
attributes[Attribute.strength] = 10;
---

However, you might prefer an Enumap to an associative array if:

You like syntactic sugar:
---
// Boring!
if (hero.attributes[Attribute.wisdom] < 5) 
hero.drink(unidentifiedPotion);

// Fun! And Concise!
if (hero.attributes.wisdom < 5) hero.drink(unidentifiedPotion);
---

You like ranges:
---
// roll for stats!
attributes = generate!(() => uniform!"[]"(1, 20)).take(6);
---

You like default values:
---
int[Attribute] aa;
Enumap!(Attribute, int) em;

aa[Attribute.strength]; // Range violation!
em.strength;            // 0
---

You like array-wise operations:
---
// note the convenient constructor function:
auto bonus = enumap(Attribute.charisma, 2, Attribute.wisdom, 1);

// level up! adds 2 to charisma and 1 to wisdom.
hero.attributes += bonus;
---

You dislike garbage day:
---
       void donFancyHat(int[Attribute] aa) { 
aa[Attribute.charisma] += 1; }
@nogc void donFancyHat(Enumap!(Attribute, int) map) { 
map.charisma += 1; }
---

Check it out, report bugs and all that!

P.S.

The above example used to read:
attributes = sequence!((a,n) => uniform!"[]"(1, 20)).take(6);
before Gary's recently posted article at 
http://nomad.so/2015/08/more-hidden-treasure-in-the-d-standard-library/ made me realize generate existed.


More information about the Digitalmars-d-announce mailing list