Module 3 – Turn repeated reasoning into small components
A function makes a promise about a result
The function below answers one question: how many lessons remain? Its inputs and result are Natural, Ada's predefined subtype of nonnegative integers. Our explicit policy is that an equal or larger completed count leaves zero remaining. Read the early return before the subtraction: it prevents a negative result for the stated input domain.
with Ada.Text_IO;
procedure Main is
function Remaining (Total, Done : Natural) return Natural is
begin
if Done >= Total then
return 0;
end if;
return Total - Done;
end Remaining;
begin
Ada.Text_IO.Put_Line (Natural'Image (Remaining (4, 1)));
end Main;The call produces three remaining lessons, printed with a leading space by Natural'Image. Trace calls with (4, 4), (4, 5), and (0, 0). For each, identify which return is reached. A useful function name and a written policy let a reviewer judge the behavior independently of the implementation.
Reference: AdaCore: functions, procedures, and parameters.
Complete this lesson
Answer every check correctly to earn your lesson certificate. Feedback helps you review and try again.
Sign in · Save your progress and earn a certificate for this lesson.