-- Inputs 2 numbers in range 0 .. 999 and prints whether they are reverse of each other
-- Demonstrates Expression functions
-- Available only in Ada 2012
pragma Ada_2012; -- Make sure 2012 compiler is used. Needed for expression functions.
with ada.text_io; use ada.text_io;
with ada.integer_text_io; use ada.integer_text_io;
procedure expr_func1 is
subtype Digit is Natural range 0 .. 9;
subtype Small_Nat is Natural range 0 .. 999;
function ones_dig(n: Small_Nat) return Digit is
(n mod 10);
function tens_dig(n: Small_Nat) return Digit is ((n / 10) mod 10);
function hundreds_dig(n: Small_Nat) return Digit is (n / 100);
-- This could be an expression function, but we'll leave it as a regular function
function eq_rev(n1, n2: Small_Nat) return Boolean is
eq1, eq10, eq100: Boolean;
begin
eq1 := ones_dig(n1) = hundreds_dig(n2);
eq10 := tens_dig(n1) = tens_dig(n2);
eq100 := hundreds_dig(n1) = ones_dig(n2);
return eq1 and eq10 and eq100;
end eq_rev;
s1, s2: Small_Nat;
begin
get(s1);
get(s2);
if eq_rev(s1, s2) then -- How could you improve this if?
put_line(s1'img & " and " & s2'img & " are THE SAME in reverse");
else
put_line(s1'img & " and " & s2'img & " are DIFFERENT in reverse");
end if;
exception
when constraint_error => put_line("Value out of range");
when others => put_line("Error occurred");
end expr_func1;
-- Input: 123 321
-- Output: 123 and 321 are THE SAME in reverse
-- Input: 123 123
-- Output: 123 and 123 are DIFFERENT in reverse