G. Generics - JulTob/Ada GitHub Wiki
We write a generic unit when a package or algorithm has the same structure for several choices, of types or operations.
Instead of writing the same algorithm once for Integer, once for Float and once for our own Numeric type, we can write it once. Then we tell the compiler how to connect the dots.
Its formal parameters describe what algebra it needs: types, objects, subprograms or packages. An instantiation supplies the actual parameters and declares a particular package, procedure or function.
For a generic algorithm, the formal type and operations establish the vocabulary available inside its implementation. The compiler checks the generic and the actual-parameter requirements under the language's generic contract rules.
We distinguish this parameterisation from run-time elaboration. Elaborating an instantiation can evaluate actual parameters and elaborate the instance. Generics are not simply a mechanism for defining previously unknown types at run time.
In Ada, a generic is like saying "Here's a recipe for ice cream." The recipe does not name a flavour yet. It only says what it needs: "some fruit, and a way to sweeten it". From that one recipe we can prepare many specific flavours. Each flavour is a real dish we can eat. The recipe itself is not.
Three words carry the whole idea:
| Word | Meaning | In the recipe |
|---|---|---|
| Generic unit | The template: a generic package, procedure or function. | The recipe. |
| Formal parameters | What the template needs from outside. | The list of ingredients. |
| Instance | A real package, procedure or function made from the template. | One cone of Stracciatella. |
We make an instance with an instantiation: is new. The instantiation supplies the actual parameters (the real ingredients), and declares a particular package, procedure or function.
A generic formal parameter can be one of four kinds of things. This is one of the places where Ada goes further than an ordinary subprogram, which can only receive objects.
formal |
It says... | Example |
|---|---|---|
| Type | "Give me a type of this family." | type Item is private; |
| Object | "Give me a value (or a variable)." | Size : in Positive; |
| Subprogram | "Give me an operation." | with function "<" (Left, Right : Item) return Boolean; |
| Package | "Give me an instance of another generic." | with package Shapes is new Generic_Shapes (<>); |
The families of formal types (
private,(<>),range <>,digits <>,delta <>...) are explained in G.T. Generic Types.
Here is the most important idea of generics:
For a generic algorithm, the formal types and the formal operations establish the vocabulary available inside its implementation.
Inside the body, we may only use the words the formal part gave us. Nothing more.
If the formal part says type Item is private;, the body knows very little about an Item. It can copy it (:=), compare it for equality (=, /=), and, from Ada 2022, turn it into text with 'Image. Any other operation on an Item, such as "<" or "+", must be asked for in the formal part.
This limits what the body can do with an Item, not how much the generic can do. A generic can declare its own helper functions, use other libraries, and work freely with types it already knows, such as Integer or String. The only rule is this: every operation on an Item is either given by the formal part, or built from what the formal part gave.
This works like a contract in two directions:
- The generic: "I only use what my formal part lists." The compiler checks this when the generic itself is compiled, before anyone instantiates it.
- The instantiation: "My actual parameters provide the formals."
- The compiler checks this at each
is new.
This pair of checks is called the generic contract model.
Because of it, a correct generic stays correct for every legal instance.
The body never has to be checked again.
Note for C++ readers. This is where Ada generics differ from C++ templates. A C++ template body is mostly checked when it is used, so its errors appear in the user's code, often far from their cause. An Ada generic body is checked once, against its own formal part, so its errors appear where they belong: in the generic.
Let us see it work with an example.
We want a function that returns the larger of two values. What does it need? Only two words: a type, and a way to say "smaller than".
generic_maximum.ads
generic
type Item is private;
--# Item can be any type that can be copied and compared with "=".
--# We know nothing else about it.
with function "<" (
Left : in Item;
Right : in Item
)
return Boolean is <>;
--# We also need to know which of two Items is the smaller one.
--# The box (<>) means: "if the instantiation does not say otherwise,
--# use the '<' that is visible where the instance is made."
function Generic_Maximum (
Left : in Item;
Right : in Item
)
return Item;generic_maximum.adb
function Generic_Maximum (
Left : in Item;
Right : in Item
)
return Item
is
--# Our whole vocabulary here is: Item, ":=", "=" and "<".
begin
if Left < Right then
return Right;
else
return Left;
end if;
end Generic_Maximum;The recipe is ready. Now we make three ice-creams from it.
show_maximum.adb
with Ada.Text_IO;
with Generic_Maximum;
procedure Show_Maximum is
type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
--# Enumeration types come with "<" for free:
----# Mon < Tue < ... < Sun.
function Maximum is new Generic_Maximum (Item => Integer);
function Maximum is new Generic_Maximum (Item => Day);
--# Two instances with the same name: they are overloaded.
--# Ada picks the right one by looking at the types of the arguments.
function Minimum is new Generic_Maximum (
Item => Integer,
"<" => ">"
);
--# Same algorithm, different operation.
--# If we hand it ">" as its idea of "smaller than",
--# the "larger" value it returns is really the smaller one.
begin
Ada.Text_IO.Put_Line (Integer'Image (Maximum (3, 7)));
Ada.Text_IO.Put_Line (Day'Image (Maximum (Tue, Sat)));
Ada.Text_IO.Put_Line (Integer'Image (Minimum (3, 7)));
end Show_Maximum;7 SAT 3
Take a look at Minimum. We did not write a new algorithm. We changed the vocabulary
we gave to the generic. This is why formal subprograms are so powerful:
the algorithm is written in terms of operations, and we choose what those operations mean.
What happens if the body tries to use a word it was not given?
Suppose we wanted the average instead of the maximum:
return (Left + Right) / 2;
--# Rejected when the GENERIC is compiled.
--# Item has no "+" and no "/": the formal part never promised them.The compiler stops here, inside generic_maximum.adb, before any instance exists.
To make it legal, we must add "+" and "/" to the formals.
And then every instantiation must provide them.
We must distinguish two different moments:
-
Parameterisation happens in the source text.
- The
is newline says which types and operations fill the template. - The compiler knows them, and checks them, at compile time.
- The
-
Elaboration happens at run time.
- First evaluates the actual parameters, then elaborates the instance declaration and its body.
So an instantiation written inside a subprogram is elaborated every time that subprogram runs. Its actual parameters can depend on run-time values, such as the value of a formal object, or the bounds of a subtype:
show_best.adb
with Ada.Text_IO;
with Generic_Maximum;
procedure Show_Best (
Top : in Natural
)
is
subtype Score is Integer range 0 .. Top;
--# The upper limit of Score is only known when Show_Best is called.
function Best is new Generic_Maximum (Item => Score);
--# This instance is elaborated each time Show_Best runs,
--# right after the subtype above it.
begin
Ada.Text_IO.Put_Line (Score'Image (Best (4, 9)));
exception
when Constraint_Error =>
Ada.Text_IO.Put_Line ("Scores must be in 0 .." & Natural'Image (Top));
end Show_Best;With Show_Best (10) it prints 9.
With Show_Best (5) the value 9 does not fit in Score,
so the call raises Constraint_Error and we report it.
But notice what did not change at run time: the kind of type.
Score is an Integer subtype, and its "<" was chosen when the program was compiled.
Only its range came from run time.
That is why generics are not a mechanism for defining unknown types at run time. Every type an instance uses is named in the source text, in an is new. A generic is a tool for writing an algorithm once. For many types.
The formal part gives only "<". The package builds four functions from it:
generic
type Item is private;
with function "<" (
Left : in Item;
Right : in Item
)
return Boolean is <>;
package Order is
function "<=" (Left, Right : in Item) return Boolean;
function Maximum (Left, Right : in Item) return Item;
function Minimum (Left, Right : in Item) return Item;
function Is_Between (X, Low, High : in Item) return Boolean;
--# Four new functions, all built from "<", "=" and ":=".
end Order;package body Order is
function "<=" (Left, Right : in Item) return Boolean is
begin
return Left < Right or else Left = Right;
--# A new word, made from two words we were given.
end "<=";
function Maximum (Left, Right : in Item) return Item is
begin
if Left < Right then
return Right;
else
return Left;
end if;
end Maximum;
function Minimum (Left, Right : in Item) return Item is
begin
if Right < Left then
return Right;
else
return Left;
end if;
--# Note: we write "Right < Left", not "Left > Right".
--# ">" was never given to us.
end Minimum;
function Is_Between (X, Low, High : in Item) return Boolean is
begin
return Low <= X and then X <= High;
--# Uses our own "<=", built a few lines above.
end Is_Between;
end Order;Notice the trap in Minimum. Even ">" is not available, although it feels obvious. The contract gave you "<" and nothing else, so Left > Right would be rejected. You either rewrite it as Right < Left, or you build your own ">" the same way "<=" was built.
| What the compiler would reject | why |
|---|
return Left + Right; | no "+" in the vocabulary
return Left > Right; | no ">" either, unless we build it
Put_Line (Item'Image (X)); | rejected in Ada 2012, legal in Ada 2022
