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 map.name as an alias to map[K.name]

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

Examples

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 = hero.attributes.byValue.map!(x => x + 1);

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

Functions

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

Structs

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

Authors

Ryan Roden-Corrent (rcorre)

Copyright

© 2015, Ryan Roden-Corrent

License

MIT