A literal inside a enumeration is a discrete type so we can use attribute Image
to find out which literal it is as text form. Notice that this prints out the same word as in the code (but in upper case).
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type Fruit is (Banana, Pear, Orange, Melon);
begin
for I in Fruit loop
Put (Fruit'Image (I));
New_Line;
end loop;
end;
BANANA
PEAR
ORANGE
MELON
Instead of attribute Image
and Ada.Text_IO.Put
on enumeration literals we can only use the generic package Ada.Text_IO.Enumeration_IO
to print out the literals.
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type Fruit is (Banana, Pear, Orange, Melon);
package Fruit_IO is new Enumeration_IO (Fruit); use Fruit_IO;
begin
for I in Fruit loop
Put (I);
New_Line;
end loop;
end;
BANANA
PEAR
ORANGE
MELON
Attribute Image
capitalizes all characters of enumeration literals. The function Case_Rule_For_Names
applies upper case for the first character and makes the rest lower case.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Maps.Constants; use Ada.Strings.Maps.Constants;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure Main is
type Fruit is (Banana, Pear, Orange, Melon);
function Case_Rule_For_Names (Item : String) return String is
begin
return Translate (Item (Item'First .. Item'First), Upper_Case_Map) & Translate (Item (Item'First + 1 .. Item'Last), Lower_Case_Map);
end;
begin
for I in Fruit loop
Put (Case_Rule_For_Names (Fruit'Image (I)));
New_Line;
end loop;
end;
Banana
Pear
Orange
Melon
Combining change of character case with Enumeration_IO and using a text buffer for the image. The first character is manipulated in place.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Handling; use Ada.Characters.Handling;
procedure Main is
type Fruit is (Banana, Pear, Orange, Melon);
package Fruit_IO is new Enumeration_IO (Fruit);
Buffer : String (1 .. Fruit'Width);
begin
for I in Fruit range Pear .. Fruit'Last loop
Fruit_IO.Put (To => Buffer,
Item => I,
Set => Lower_Case);
Buffer (Buffer'First) := To_Upper (Buffer (Buffer'First));
Put_Line (Buffer);
end loop;
end;
Pear
Orange
Melon