Switch in Ada

Here’s a set of examples demonstrating the usage of switch statements.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar;

procedure Switch is

begin
    -- Here’s a basic switch.
    declare
        I : Integer := 2;
    begin
        Put("Write ");
        Put(I'Image);
        Put(" as ");
        case I is
            when 1 =>
                Put_Line("one");
            when 2 =>
                Put_Line("two");
            when 3 =>
                Put_Line("three");
            when others =>
                null;
        end case;
    end;

    -- Multiple expressions in one case
    declare
        Today : Ada.Calendar.Day_Of_Week := Ada.Calendar.Day_Of_Week(Ada.Calendar.Clock);
    begin
        case Today is
            when Ada.Calendar.Saturday | Ada.Calendar.Sunday =>
                Put_Line("It's the weekend");
            when others =>
                Put_Line("It's a weekday");
        end case;
    end;

    -- Switch without an expression is similar to if/else logic
    declare
        T : Ada.Calendar.Time := Ada.Calendar.Clock;
        Hour : Integer := Ada.Calendar.Hour(T);
    begin
        if Hour < 12 then
            Put_Line("It's before noon");
        else
            Put_Line("It's after noon");
        end if;
    end;

    -- Type switch to discover types, though Ada is more strongly typed
    declare
        type My_Type is tagged null record;
        type Bool_Type is new My_Type with null record;
        type Int_Type is new My_Type with null record;
        type String_Type is new My_Type with null record;

        procedure What_Am_I(I : access My_Type'Class) is
        begin
            if I in Bool_Type'Class then
                Put_Line("I'm a bool");
            elsif I in Int_Type'Class then
                Put_Line("I'm an int");
            elsif I in String_Type'Class then
                Put_Line("I'm a string");
            else
                Put_Line("Don't know type");
            end if;
        end What_Am_I;

        B : aliased Bool_Type;
        N : aliased Int_Type;
        S : aliased String_Type;
    begin
        What_Am_I(B'access);
        What_Am_I(N'access);
        What_Am_I(S'access);
    end;

end Switch;

To compile and run the Ada code, save the code into a file named switch.adb and use the following commands:

$ gnatmake switch.adb
$ ./switch

The output should be:

Write  2. as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type