Enums in Ada

Our enum type ServerState has an underlying int type.

type ServerState is (StateIdle, StateConnected, StateError, StateRetrying);

The possible values for ServerState are defined as constants. Since Ada enums automatically assign consecutive values starting from 0, you don’t need to manually assign values as you would in other languages.

By implementing a Stringer equivalent, values of ServerState can be printed out or converted to strings.

with Ada.Text_IO; use Ada.Text_IO;

function To_String (State : ServerState) return String is
begin
   case State is
      when StateIdle       => return "idle";
      when StateConnected  => return "connected";
      when StateError      => return "error";
      when StateRetrying   => return "retrying";
   end case;
end To_String;

If we have a value of type ServerState, we can pass it to the transition function, which will return a new state.

procedure Main is
   function Transition (State : ServerState) return ServerState is
   begin
      case State is
         when StateIdle       => return StateConnected;
         when StateConnected  => return StateIdle;
         when StateRetrying   => return StateIdle;
         when StateError      => return StateError;
         when others          => raise Program_Error;
      end case;
   end Transition;

   Ns   : ServerState := Transition(StateIdle);
   Ns2  : ServerState := Transition(Ns);

begin
   Put_Line(To_String(Ns));
   Put_Line(To_String(Ns2));
end Main;

To run the program, save the code in a file, for example, enums.adb, and use GNAT (the GNU Ada compiler) to compile and run it.

$ gnatmake enums.adb
$ ./enums
connected
idle

This demonstrates basic enum type handling and state transitions in Ada. Ada’s strong type system ensures that the compiler will catch type mismatches, providing compile-time type safety.