Skip to content

Commit 8a300e0

Browse files
committed
subtypes: add idiom for ad-hoc subtypes
1 parent c882dff commit 8a300e0

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

courses/fundamentals_of_ada/030_basic_types/11-subtypes_full_picture.rst

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,43 @@ Idiom: Partition
253253
Execute_Light_Command (C);
254254
...
255255
256+
--------------------------------------
257+
Idiom: Subtypes as Local Constraints
258+
--------------------------------------
259+
260+
* Can replace defensive code
261+
* Can be very useful in some identified cases
262+
* Subtypes accept dynamic bounds, unlike types
263+
* Checks happens through type-system
264+
265+
- Can be disabled with :command:`-gnatp`, unlike conditionals
266+
- Can also be a disadvantage
267+
268+
.. warning::
269+
270+
Do not use for checks that should **always** happen, even in production.
271+
272+
.. code:: Ada
273+
274+
subtype Incrementable_Integer is Integer
275+
range Integer'First .. Integer'Last - 1;
276+
277+
function Increment (I : Incrementable_Integer) return Integer;
278+
279+
.. code:: Ada
280+
281+
subtype Valid_Fingers_T is Integer
282+
range 1 .. 5;
283+
Fingers : Valid_Fingers_T
284+
:= Prompt_And_Get_Integer ("Give me the number of a finger");
285+
286+
.. code:: Ada
287+
288+
function Read_Index_And_Manipulate_Char (S : String) is
289+
subtype S_Index is Positive range S'Range;
290+
I : constant S_Index := Read_Positive;
291+
C : Character renames S (I);
292+
256293
------
257294
Quiz
258295
------

0 commit comments

Comments
 (0)