Skip to content

Commit 001668c

Browse files
committed
subtypes: add idiom for ad-hoc subtypes
1 parent 611d947 commit 001668c

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

0 commit comments

Comments
 (0)