Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada Enums to Values

Tags:

enums

ada

I could handle this in a not as clean way, but I was hoping to take advantage of the following:

type Prefix is (Yocto, Zepto, Atto, Femto, Pico, Nano,
    Micro, Milli, Centi, Deci, None, Deca, Hecto, Kilo,
    Mega, Giga, Tera, Peta, Exa, Zetta, Yotta);
for Prefix use (
    Yocto => -24,
    Zepto => -21,
    Atto => -18,
    Femto => -15,
    Pico => -12,
    Nano => -9,
    Micro => -6,
    Milli => -3,
    Centi => -2,
    Deci => -1,
    None => 0,
    Deca => 1,
    Hecto => 2,
    Kilo => 3,
    Mega => 6,
    Giga => 9,
    Tera => 12,
    Peta => 15,
    Exa => 18,
    Zetta => 21,
    Yotta => 24);

GNAT doesn't complain about the representation clause. However, I can't seem to actually get the value out, since the only attributes related to this, that I am aware of, have to do with position, not assigned value.

like image 925
Patrick Kelly Avatar asked Dec 08 '22 04:12

Patrick Kelly


2 Answers

Enumerations were never intended for this sort of purpose, and you shouldn't try to use them for that. (I think the main purpose was to define enumerations that had values other than 0, 1, ... in some external representation or a hardware register or something.) However, you can actually fix this while keeping your code almost the same:

type Prefix is (Yocto, Zepto, Atto, Femto, Pico, Nano,
    Micro, Milli, Centi, Deci, None, Deca, Hecto, Kilo,
    Mega, Giga, Tera, Peta, Exa, Zetta, Yotta);
type Prefix_To_Integer_Map is array (Prefix) of Integer;
Power_of_Ten : constant Prefix_To_Integer_Map := (
    Yocto => -24,
    Zepto => -21,
    Atto => -18,
    Femto => -15,
    Pico => -12,
    Nano => -9,
    Micro => -6,
    Milli => -3,
    Centi => -2,
    Deci => -1,
    None => 0,
    Deca => 1,
    Hecto => 2,
    Kilo => 3,
    Mega => 6,
    Giga => 9,
    Tera => 12,
    Peta => 15,
    Exa => 18,
    Zetta => 21,
    Yotta => 24);

Should be about as clean as what you had. And saying Power_Of_Ten (My_Prefix) is more descriptive than My_Prefix'Enum_Rep or Prefix'Enum_Rep(My_Prefix) or whatever it is.

like image 157
ajb Avatar answered Feb 07 '23 10:02

ajb


If an implementation defined attribute is acceptable, GNAT provides two attributes that are useful in this context:

  • Enum_Rep, which "returns the representation value for the given enumeration value."

  • Enum_Val, which "returns the enumeration value whose representation matches the argument."

like image 40
trashgod Avatar answered Feb 07 '23 10:02

trashgod