Skip to content

Latest commit

 

History

History
109 lines (59 loc) · 2.7 KB

image-for-any-type.md

File metadata and controls

109 lines (59 loc) · 2.7 KB

Ada 2020: 'Image attribute for any type

This post is a part of the Ada 2020 series.

You can launch this notebook with Jupyter Ada Kernel by clicking this button:

Binder

Ada 2020 activation

Firstly, let's activate Ada 2020 support in the compiler. Usually we do this by -gnat2020 option in compiler command line or in the project file (preferred). But in this notebook we will do this by the pragma Ada_2020. Also we will need the Text_IO package.

pragma Ada_2020;

with Ada.Text_IO;

X'Image attribute

If you missed Technical Corrigendum 1 changes (they were published in February 2016) then you probably don't know that the 'Image attribute can be applied now to a value. So, instead of My_Type'Image (Value) you can just write Value'Image, but only if the Value is a name. So, these two statements are equal:

Ada.Text_IO.Put_Line (Ada.Text_IO.Page_Length'Image);

Ada.Text_IO.Put_Line
  (Ada.Text_IO.Count'Image (Ada.Text_IO.Page_Length));
 0
 0

'Image in Ada 2020 works for any type

Now you can apply 'Image attribute for any type, including records, array, access and private types. Let's see how this works.

type Vector is array (Positive range <>) of Integer;

V1 : aliased Vector := (1, 2, 3);

type Text_Position is record
   Line, Column : Positive;
end record;
                      
Pos : Text_Position := (Line => 10, Column => 3);
                      
type Vector_Access is access all Vector;

V1_Ptr : Vector_Access := V1'Access;

Now you can convert these objects to string and print:

Ada.Text_IO.Put_Line (V1'Image);

Ada.Text_IO.Put_Line (Pos'Image);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (V1_Ptr'Image);
[ 1,  2,  3]

(line =>  10,
 column =>  3)

(access 7ff5c5717138)

Note square brackets in array image. In Ada 2020 array aggregates could be written this way!

References

More details:


Do you like this? Support us on patreon!

Live discussions: Telegram, Matrix.