Module enumap
An
maps each member of an enum to a single value.
Enumap
An
is effectively a lightweight associative array with some benefits.
Enumap
You can think of an
somewhat like a Enumap
!(MyEnum, int)int[MyEnum]
,
with the following differences:
-
is a value type and requires no dynamic memory allocation
Enumap
!(K,V)
-
has a pre-initialized entry for every member of Enumap
!(K,V)K
-
supports the syntax Enumap
!(K,V)map.name
as an alias to map[K.name]
-
supports array-wise operations
Enumap
!(K,V)
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
s:
Enumap
// 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
down into a range when needed:
Enumap
hero.attributes = hero.attributes.byValue.map!(x => x + 1);
See the full documentation of
for all the operations it supports.
Enumap
Functions
Name | Description |
---|---|
enumap
|
Construct an 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