Skip to content

Commit 611d947

Browse files
committed
subtypes: add some idioms
1 parent badabd2 commit 611d947

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

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

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,85 @@ Attributes Reflect the Underlying Type
175175
Shade : Color range Red .. Blue := Brown; -- run-time error
176176
Hue : Rainbow := Rainbow'Succ (Blue); -- run-time error
177177
178+
------------------------
179+
Idiom: Extended Ranges
180+
------------------------
181+
182+
* ``Count`` / ``Positive_Count``
183+
184+
- Sometimes as ``Type_Ext`` (extended) / ``Type``
185+
- For counting vs indexing
186+
187+
+ An index goes from 1 to max length
188+
+ A count goes from 0 to max length
189+
190+
.. code:: Ada
191+
192+
-- ARM A.10.1
193+
package Text_IO is
194+
...
195+
type Count is range 0 .. implementation-defined;
196+
subtype Positive_Count is Count range 1 .. Count'Last;
197+
198+
---------------------
199+
Idiom: Option Types
200+
---------------------
201+
202+
* **Great** use case for the ``Default_Value`` aspect
203+
204+
.. code:: Ada
205+
206+
declare
207+
type Maybe_Result_T is (None, Greater, Smaller)
208+
with Default_Value => None;
209+
subtype Result_T is Maybe_Result_T range Greater .. Smaller;
210+
211+
function Get_Result return Result_T;
212+
procedure Display_Result (R : Result_T);
213+
214+
R : Result_T; -- run-time error and GNAT warning
215+
Maybe_R : Maybe_Result_T; -- default "None" value
216+
begin
217+
Display_Result (Maybe_R); -- run-time error
218+
-- Ok
219+
Maybe_R := Get_Result;
220+
Display_Result (Maybe_R);
221+
222+
------------------
223+
Idiom: Partition
224+
------------------
225+
226+
* Useful for splitting-up large enums
227+
228+
.. warning::
229+
230+
Be careful about checking that the partition is complete when
231+
items are added removed.
232+
Using at least a single :ada:`case` will check that for you.
233+
234+
.. tip::
235+
236+
Can have non-consecutive values with the :ada:`Predicate` aspect.
237+
238+
.. code:: Ada
239+
240+
type Commands_T is (Lights_On, Lights_Off, Read, Write, Accelerate, Stop);
241+
-- Complete partition of the commands
242+
subtype IO_Commands_T is Commands_T range Read .. Write;
243+
subtype Lights_Commands_T is Commands_T range Lights_On .. Lights_Off;
244+
subtype Movement_Commands_T is Commands_T range Accelerate .. Stop;
245+
246+
subtype Physical_Commands_T is Commands_T
247+
with Predicate => Physical_Commands_T in Lights_Commands_T | Movement_Commands_T;
248+
249+
procedure Execute_Light_Command (C : Lights_Commands_T);
250+
251+
procedure Execute_Command (C : Commands_T) is
252+
begin
253+
case C in -- partition must be exhaustive
254+
when Lights_Commands_T => Execute_Light_Command (C);
255+
...
256+
178257
------
179258
Quiz
180259
------

0 commit comments

Comments
 (0)