Working with the role behind the enum type
This is the role implemented by the enum-pairs in the
enum type. In general, it is used to create constant sets, the elements of which become also constant symbols in the current namespace and to establish a relationship between the symbols belonging to the same set. In general, you will find
Enumeration in enum types:
<Þor Oðin Loki>;my = norse-gods.pick;say ~~ Enumeration; # OUTPUT: «True␤»
but nothing prevents you from using it in your own programs if you want to restrict somehow the relationship between the key and the value:
does Enumeration();constant length = 16;for <A C G T>.roll( length ) ->for ^length
In this code,
DNA consumes the
Enumeration role, which is from this point of view a pair of key and value; we can use the generated
DNA objects to compose an
enum type from which elements can be picked one by one, with the output shown below.
T and AC and GT and A# and so on...
These are the methods included in this role:
<Þor Oðin Freija>;say Freija.key; # OUTPUT: «Freija␤»
<Þor Oðin Freija>;say Oðin.value; # OUTPUT: «1␤»
value is assigned automatically by the
enum type starting at 0.
Oðin gets 1 since it is the second in the
Returns a Map of enum values. Works both on the enum type and any key.
( mg => 1/1000, g => 1/1, kg => 1000/1 );say Mass.enums; # OUTPUT: «Map.new((g => 1, kg => 1000, mg => 0.001))␤»say g.enums; # OUTPUT: «Map.new((g => 1, kg => 1000, mg => 0.001))␤»
multi method kv(::?CLASS:)
Returns a list with key and value of the enum-pair.
say g.kv; # OUTPUT: «(g 1)␤»
Returns it as a
say g.pair; # OUTPUT: «g => 1␤»
multi method pick(::?CLASS:)multi method pick(::?CLASS: \n)multi method pick(::?CLASS: *)
It works on the defined class, selecting one element and eliminating it.
say Norse-gods.pick() for ^3; # OUTPUT: «Þor␤Freija␤Oðin␤»
multi method roll(::?CLASS:)multi method roll(::?CLASS: \n)multi method roll(::?CLASS: *)
They work on the defined class selecting one or
n elements without eliminating them.
say Norse-gods.roll() for ^3; # OUTPUT: «Freija␤Freija␤Oðin␤»
say Freija.pred; # OUTPUT: «Oðin␤»
say Oðin.succ; # OUTPUT: «Freija␤»
multi method Int(::?CLASS:)
Takes a value of an enum and returns it after coercion to
<One Two Three>;say Two.Int; # OUTPUT: «1␤»
( cool => '42', almost-pi => '3' );say cool.Int; # OUTPUT: «42␤»say almost-pi.Int; # OUTPUT: «3␤»
Note that if the value cannot be coerced to
Int, an exception will be thrown.
multi infix:<===> (Enumeration \a, Enumeration \b)
say Norse-gods.pick() === Freija for ^3; # OUTPUT: «False␤False␤True␤»