Module enumap

An Enumap maps each member of an enum to a single value.

An Enumap is effectively a lightweight associative array with some benefits.

You can think of an Enumap!(MyEnum, int) somewhat like a int[MyEnum], with the following differences:

- Enumap!(K,V) is a value type and requires no dynamic memory allocation

- Enumap!(K,V) has a pre-initialized entry for every member of K

- Enumap!(K,V) supports the syntax as an alias to map[]

- Enumap!(K,V) supports array-wise operations


Suppose you are building a good ol' dungeon-crawling RPG. Where to start? How about the classic 6 attributes:

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

struct Character {
 Enumap!(Attribute, int) attributes;

Lets roll some stats!

Character hero;
hero.attributes = sequence!((a,n) => uniform!"[]"(0, 20))().take(6);

Note that we can assign directly from a range! Just like static array assignment, it will fail if the length doesn't match.

We can access those values using either opIndex or opDispatch:

if (hero.attributes[Attribute.wisdom] < 5) hero.drink(unidentifiedPotion);
// equivalent
if (hero.attributes.wisdom < 5) hero.drink(unidentifiedPotion);

We can also perform binary operations between Enumaps:

// note the convenient assignment from an associative array:
Enumap!(Attribute, int) bonus = {Attribute.charisma: 2, Attribute.wisom: 1};

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

Finally, note that we can break the Enumap down into a range when needed:

hero.attributes =!(x => x + 1);

See the full documentation of Enumap for all the operations it supports.


Name Description
enumap Construct an Enumap from a sequence of key/value pairs.


Name Description
Enumap A structure that maps each member of an enum to a single value.


Ryan Roden-Corrent (rcorre)


© 2015, Ryan Roden-Corrent