comp.lang.ada
 help / color / mirror / Atom feed
Search results ordered by [date|relevance]  view[summary|nested|Atom feed]
thread overview below | download mbox.gz: |
* Valid attribute and input operations
@ 2023-09-23 20:22  4% Maciej Sobczak
  0 siblings, 0 replies; 200+ results
From: Maciej Sobczak @ 2023-09-23 20:22 UTC (permalink / raw)


Hi there,

I am in the middle of a heated debate with Richard Riehle on LinkedIn, where we cannot get to terms with regard to the exact semantics of X'Valid in the context of input operations performed by standard Get procedure.
In short, consider the following example:

with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Is_Valid_Test is
   X : Integer range 0..200;
begin
   Ada.Text_IO.Put("Get an Integer: ");
   Ada.Integer_Text_IO.Get(X);
   if X'Valid then
      Ada.Text_IO.Put_Line("The Input is Valid ");
   else
      Ada.Text_IO.Put_Line("The Input is not Valid ");
   end if;
end Is_Valid_Test;

When the input is 500, what should be the behavior of this program?
There are two interpretations:

1. Get is an input operation and can create invalid representations (as stated in 13.9.2, p.7). Then, the X'Valid test that follows Get(X) can be used to safely recognize whether the value is in the range or not. The program should print the second string (from the else branch), but should not raise any exceptions for this input (500).

2. Get is not an input operation in the meaning referred to in 13.9.2/7, or is an input, but only for type Integer (and it cannot create invalid integer representations on typical computers anyway). The X variable is an actual parameter that has a subtype that is different from the formal parameter and is subject to conversions when the Get subprogram exits normally (6.4.1/17,17a). This conversion should raise Constraint_Error for this input (500).

I have checked the above program on several on-line compilers, all of them behave according to interpretation 2 above.
Richard claims to get behavior 1 on his compiler.

What is your take on this? Any language lawyers?

Regards,
Maciej Sobczak

^ permalink raw reply	[relevance 4%]

* Re: When using the Ada Big_Numbers.Big_Integers package, can the To_String function output be sliced?
  2023-07-29 23:53  5%           ` Kenneth Wolcott
@ 2023-07-30  4:43  4%             ` Randy Brukardt
  0 siblings, 0 replies; 200+ results
From: Randy Brukardt @ 2023-07-30  4:43 UTC (permalink / raw)


'Image doesn't support any formatting, so no "Aft" or "Exp". The slicing 
isn't the problem. :-)

You can use Text_IO to write to a string if you need formatting. 'Image is 
for quick & dirty debugging, not fancy output. (Of course, if you're lucky 
and it does what you need, then feel free to use it.)

                                 Randy.

"Kenneth Wolcott" <kennethwolcott@gmail.com> wrote in message 
news:2a5702b3-dbbc-4255-a4d4-e801f227fed3n@googlegroups.com...
On Saturday, July 29, 2023 at 4:49:08?PM UTC-7, Kenneth Wolcott wrote:
> On Saturday, July 29, 2023 at 4:07:17?AM UTC-7, AdaMagica wrote:
> > > Powers_of_2 := Powers_of_2 * To_Big_Integer (2);
> > With the aspect Integer_Literal, also Powers_of_2 * 2 must work. The 
> > attributes Integer_Literal, Real_Literal, Put_Image make the new big 
> > numbers nearly work like numeric types (they are not). A difference: The 
> > range syntax for instance in loops A .. B is illegal.
> I understand that the range syntax in loops implies that the loop variable 
> is acting like an enumerated type which is not true for Big_Integers.
>
> What confused me is that I thought I had to convert the numeric literal 
> (I'll have to go back and look at the package spec again to get this 
> firmly understood.
>
> I have an another question about string slicing: I've tried (obviously 
> incorrectly) to use a variable is one of the slice integers. Can this be 
> done?
>
> Thanks,
> Ken

Apparently not :-(

gnatmake main.adb
gcc -c main.adb
main.adb:28:67: error: named parameters not permitted for attributes
     9 with Ada.Text_IO; use Ada.Text_IO;
    10 with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
    11 with Ada.Float_Text_IO; use Ada.Float_Text_IO;
    12 with Ada.Numerics.Elementary_Functions; use 
Ada.Numerics.Elementary_Functions;
    13 with Ada.Command_Line; use Ada.Command_Line;
    14
    15 procedure Main is
    16   Substr : String := Argument (1);
    17   Nth : Positive := Integer'Value (Argument (2));
    18   I, J : Natural;
    19   Temp : Float;
    20 begin
    21   I := 0;
    22   J := 0;
    23   loop
    24     I := I + 1;
    25     exit when I >= 10;
    26     Temp := 10.0 ** (log (2.0, 10.0) * Float (I));
    27     if I >= 4  then
    28       if (Float'Image (10.0 ** (log (2.0, 10.0) * Float (I)), Aft => 
0, Exp => 0) (1 .. Substr'Length) = Substr then
    29         J := J + 1;
    30         if J = Nth then
    31           Put (I, 0);
    32           New_Line;
    33           exit;
    34         end if;
    35       end if;
    36     end if;
    37   end loop;
    38 end Main;

Thanks,
Ken 


^ permalink raw reply	[relevance 4%]

* Re: When using the Ada Big_Numbers.Big_Integers package, can the To_String function output be sliced?
  @ 2023-07-29 23:53  5%           ` Kenneth Wolcott
  2023-07-30  4:43  4%             ` Randy Brukardt
  0 siblings, 1 reply; 200+ results
From: Kenneth Wolcott @ 2023-07-29 23:53 UTC (permalink / raw)


On Saturday, July 29, 2023 at 4:49:08 PM UTC-7, Kenneth Wolcott wrote:
> On Saturday, July 29, 2023 at 4:07:17 AM UTC-7, AdaMagica wrote: 
> > > Powers_of_2 := Powers_of_2 * To_Big_Integer (2); 
> > With the aspect Integer_Literal, also Powers_of_2 * 2 must work. The attributes Integer_Literal, Real_Literal, Put_Image make the new big numbers nearly work like numeric types (they are not). A difference: The range syntax for instance in loops A .. B is illegal.
> I understand that the range syntax in loops implies that the loop variable is acting like an enumerated type which is not true for Big_Integers. 
> 
> What confused me is that I thought I had to convert the numeric literal (I'll have to go back and look at the package spec again to get this firmly understood. 
> 
> I have an another question about string slicing: I've tried (obviously incorrectly) to use a variable is one of the slice integers. Can this be done? 
> 
> Thanks, 
> Ken

Apparently not :-(

gnatmake main.adb
gcc -c main.adb
main.adb:28:67: error: named parameters not permitted for attributes
     9	with Ada.Text_IO; use Ada.Text_IO;
    10	with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
    11	with Ada.Float_Text_IO; use Ada.Float_Text_IO;
    12	with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
    13	with Ada.Command_Line; use Ada.Command_Line;
    14
    15	procedure Main is
    16	  Substr : String := Argument (1);
    17	  Nth : Positive := Integer'Value (Argument (2));
    18	  I, J : Natural;
    19	  Temp : Float;
    20	begin
    21	  I := 0;
    22	  J := 0;
    23	  loop
    24	    I := I + 1;
    25	    exit when I >= 10;
    26	    Temp := 10.0 ** (log (2.0, 10.0) * Float (I));
    27	    if I >= 4  then
    28	      if (Float'Image (10.0 ** (log (2.0, 10.0) * Float (I)), Aft => 0, Exp => 0) (1 .. Substr'Length) = Substr then
    29	        J := J + 1;
    30	        if J = Nth then
    31	          Put (I, 0);
    32	          New_Line;
    33	          exit;
    34	        end if;
    35	      end if;
    36	    end if;
    37	  end loop;
    38	end Main;

Thanks,
Ken

^ permalink raw reply	[relevance 5%]

* Re: When using the Ada Big_Numbers.Big_Integers package, can the To_String function output be sliced?
  @ 2023-07-27 22:47  4%   ` Kenneth Wolcott
    0 siblings, 1 reply; 200+ results
From: Kenneth Wolcott @ 2023-07-27 22:47 UTC (permalink / raw)


On Thursday, July 27, 2023 at 1:53:38 AM UTC-7, Jeffrey R.Carter wrote:
> On 2023-07-27 07:26, Kenneth Wolcott wrote: 
> > 
> > When using the Ada Big_Numbers.Big_Integers package, can the To_String function output be sliced? 
> > 
> > I'd like to slice out the first two digits from the output of the To_String function of Ada.Big_Numbers.Big_Integers. 
> > 
> > When trying to do the usual string slicing on the output I get a silent failure, it is just as if I typed the null statement.
> It would be helpful if you could show what you're doing and what results you 
> get. This 
> 
> with Ada.Numerics.Discrete_Random; 
> with Ada.Text_IO; 
> 
> procedure Func_Slice is 
> subtype Digit is Character range '0' .. '9'; 
> 
> package Random is new Ada.Numerics.Discrete_Random (Result_Subtype => Digit); 
> 
> Gen : Random.Generator; 
> 
> function Image (N : in Natural) return String is 
> (if N = 0 then "" else Random.Random (Gen) & Image (N - 1) ); 
> -- Returns a string of N random Digits 
> begin -- Func_Slice 
> Random.Reset (Gen => Gen); 
> Ada.Text_IO.Put_Line (Item => Image (10) (1 .. 2) ); 
> end Func_Slice; 
> 
> works as expected 
> 
> $ gnatmake -m -j0 -gnat12 -gnatan -gnato2 -O2 -fstack-check func_slice.adb 
> x86_64-linux-gnu-gcc-12 -c -gnat12 -gnatan -gnato2 -O2 -fstack-check func_slice.adb 
> x86_64-linux-gnu-gnatbind-12 -x func_slice.ali 
> x86_64-linux-gnu-gnatlink-12 func_slice.ali -O2 -fstack-check 
> $ ./func_slice 
> 10 
> $ ./func_slice 
> 51 

Hi Jeff;

  After going back and exhaustively reviewing the AdaCore Learning Introduction sections on Strings and Arrays, I determined that I was not slicing with the correct syntax for what I wanted to obtain, it seems that I was slicing built-in whitespace, not the digits I was looking for.  So I am now extracting the two-digit slice using (2 .. 3) rather than (1 .. 2) and I am now obtaining the desired output.  What I was trying to do was to obtain the slice from the string on the fly, not first saving the string to a variable.

This is what I have now (which works great):
---------------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers;

procedure Powers_Of_2_With_Leading_Digits_Of_12 is
  Max : Positive := Integer'Value (Argument (1));
  Powers_of_2 : Big_Positive := 1;
begin
  for I in 1 .. Max loop
    Powers_of_2 := Powers_of_2 * To_Big_Integer (2);
    if I >= 4 then
      declare
        Powers_of_2_in_String_Format : String := To_String (Powers_of_2);
        First_Pair_of_String_Digits : String := Powers_of_2_in_String_Format (2 .. 3);
      begin
        if First_Pair_of_String_Digits = "12" then
          Put ("2^");
          Put (I, 0);
          Put_Line (To_String (Powers_of_2));
        end if;
      end; -- declare
    end if;
  end loop;
end Powers_Of_2_With_Leading_Digits_Of_12;
---------------------------------------------------------------------------

Now I can generalize this to more closely match the task requirements.

I think I tried to incorrectly create the slice from the To_String output directly without creating the variable in which to store the slice, which then requires the declare block.

Thanks,
Ken

^ permalink raw reply	[relevance 4%]

* Re: Get_Line skip input
  2021-08-26  9:09  3% ` Jeffrey R. Carter
@ 2021-08-27  2:55  0%   ` Richard Iswara
  0 siblings, 0 replies; 200+ results
From: Richard Iswara @ 2021-08-27  2:55 UTC (permalink / raw)


On 26/08/2021 16.09, Jeffrey R. Carter wrote:
> On 8/26/21 7:36 AM, Richard Iswara wrote:
>>
>> So on the terminal it shows like this:
>> Keywords number 1 =  Enter Multiplier for keyword <here cursor wait 
>> for entry>
>> Keywords number 2 =  Enter Multiplier for keyword <here cursor wait 
>> for entry>
> 
> I set Kw_Numbers to 3 and added an output loop after the input loop:
> 
>     for I in Key_Words'Range loop
>        Ada.Text_IO.Put_Line (Item => I'Image & ' ' &
>                                      Key_Words (I) (1 .. W_Len (I) ) &
>                                      Multiplier (I)'Image);
>     end loop;
> 
> I am unable to duplicate this behavior:
> 
> ~/Code$ ./kw_test
> Enter keywords less than 10 characters.
> Keywords number 1 = one
> Enter multiplier for keyword 7
> 
> Keywords number 2 = Enter multiplier for keyword 6
> 
> Keywords number 3 = Enter multiplier for keyword 3
> 
>   1 one 7
>   2  6
>   3  3
> 
> As Holsti explained, this behavior is due to Ada.Integer_Text_IO.Get 
> behaving as specified, leaving the rest of the line available to Get_Line:
> 
> ~/Code$ ./kw_test
> Enter keywords less than 10 characters.
> Keywords number 1 = one
> Enter multiplier for keyword 7
> 
> Keywords number 2 = Enter multiplier for keyword 6
> 
> Keywords number 3 = Enter multiplier for keyword 3
> 
>   1 one 7
>   2  6
>   3  3
> ~/Code$ ./kw_test
> Enter keywords less than 10 characters.
> Keywords number 1 = one
> Enter multiplier for keyword 7two
> 
> Keywords number 2 = Enter multiplier for keyword 6three
> 
> Keywords number 3 = Enter multiplier for keyword 3
> 
>   1 one 7
>   2 two 6
>   3 three 3
> 
> In general, I recommend obtaining a complete line and parsing it, rather 
> than inputting values with Get:
> 
> Get_Mult : loop
>     Ada.Text_IO.Put (Item => "Enter multiplier for keyword ");
> 
>     One_Mult : declare
>        Line : constant String := Ada.Text_IO.Get_Line;
>     begin -- One_Mult
>        Multiplier (I) := Integer'Value (Line);
> 
>        exit Get_Mult;
>     exception -- One_Mult
>     when others =>
>        Ada.Text_IO.Put_Line (Item => "Enter an non-negative integer");
>     end One_Mult;
> end loop Get_Mult;
> 
> In general such code has to handle errors in the input. Users will input 
> key words > the specified max and non-numeric multipliers. Error 
> handling is simplified if one obtains complete lines (using the Get_Line 
> function) and deals with them.
> 
> Back in the Good Old Days (TM), I started off using FORTRAN 66 (it was 
> always written FORTRAN because the keypunches only had capital letters), 
> where the only data structure was the array. Things that would be an 
> array of records in a decent language were represented as groups of 
> parallel arrays. That seems to be what you're doing here.
> 
> subtype KW_Name_Length is Integer range 0 .. 10;
> 
> type Key_Word_Info (Length : KW_Name_Length := 0) is record
>     Name : String (1 .. Length);
>     Multiplier : Natural;
> end record;
> 
> Num_KW : constant := 3;
> 
> type KW_List is array (1 .. Num_KW) of Key_Word_Info;
> 
> Key_Word : KW_List;
> 
Thank you Niklas and Jeffrey for the explanation and the better way to 
do an input message.
Regards,
Richard.

^ permalink raw reply	[relevance 0%]

* Re: Get_Line skip input
  2021-08-26  5:36  5% Get_Line skip input Richard Iswara
  2021-08-26  7:56  0% ` Niklas Holsti
@ 2021-08-26  9:09  3% ` Jeffrey R. Carter
  2021-08-27  2:55  0%   ` Richard Iswara
  1 sibling, 1 reply; 200+ results
From: Jeffrey R. Carter @ 2021-08-26  9:09 UTC (permalink / raw)


On 8/26/21 7:36 AM, Richard Iswara wrote:
> 
> So on the terminal it shows like this:
> Keywords number 1 =  Enter Multiplier for keyword <here cursor wait for entry>
> Keywords number 2 =  Enter Multiplier for keyword <here cursor wait for entry>

I set Kw_Numbers to 3 and added an output loop after the input loop:

    for I in Key_Words'Range loop
       Ada.Text_IO.Put_Line (Item => I'Image & ' ' &
                                     Key_Words (I) (1 .. W_Len (I) ) &
                                     Multiplier (I)'Image);
    end loop;

I am unable to duplicate this behavior:

~/Code$ ./kw_test
Enter keywords less than 10 characters.
Keywords number 1 = one
Enter multiplier for keyword 7

Keywords number 2 = Enter multiplier for keyword 6

Keywords number 3 = Enter multiplier for keyword 3

  1 one 7
  2  6
  3  3

As Holsti explained, this behavior is due to Ada.Integer_Text_IO.Get behaving as 
specified, leaving the rest of the line available to Get_Line:

~/Code$ ./kw_test
Enter keywords less than 10 characters.
Keywords number 1 = one
Enter multiplier for keyword 7

Keywords number 2 = Enter multiplier for keyword 6

Keywords number 3 = Enter multiplier for keyword 3

  1 one 7
  2  6
  3  3
~/Code$ ./kw_test
Enter keywords less than 10 characters.
Keywords number 1 = one
Enter multiplier for keyword 7two

Keywords number 2 = Enter multiplier for keyword 6three

Keywords number 3 = Enter multiplier for keyword 3

  1 one 7
  2 two 6
  3 three 3

In general, I recommend obtaining a complete line and parsing it, rather than 
inputting values with Get:

Get_Mult : loop
    Ada.Text_IO.Put (Item => "Enter multiplier for keyword ");

    One_Mult : declare
       Line : constant String := Ada.Text_IO.Get_Line;
    begin -- One_Mult
       Multiplier (I) := Integer'Value (Line);

       exit Get_Mult;
    exception -- One_Mult
    when others =>
       Ada.Text_IO.Put_Line (Item => "Enter an non-negative integer");
    end One_Mult;
end loop Get_Mult;

In general such code has to handle errors in the input. Users will input key 
words > the specified max and non-numeric multipliers. Error handling is 
simplified if one obtains complete lines (using the Get_Line function) and deals 
with them.

Back in the Good Old Days (TM), I started off using FORTRAN 66 (it was always 
written FORTRAN because the keypunches only had capital letters), where the only 
data structure was the array. Things that would be an array of records in a 
decent language were represented as groups of parallel arrays. That seems to be 
what you're doing here.

subtype KW_Name_Length is Integer range 0 .. 10;

type Key_Word_Info (Length : KW_Name_Length := 0) is record
    Name : String (1 .. Length);
    Multiplier : Natural;
end record;

Num_KW : constant := 3;

type KW_List is array (1 .. Num_KW) of Key_Word_Info;

Key_Word : KW_List;

-- 
Jeff Carter
"Why don't you bore a hole in yourself and let the sap run out?"
Horse Feathers
49

^ permalink raw reply	[relevance 3%]

* Re: Get_Line skip input
  2021-08-26  5:36  5% Get_Line skip input Richard Iswara
@ 2021-08-26  7:56  0% ` Niklas Holsti
  2021-08-26  9:09  3% ` Jeffrey R. Carter
  1 sibling, 0 replies; 200+ results
From: Niklas Holsti @ 2021-08-26  7:56 UTC (permalink / raw)


On 2021-08-26 8:36, Richard Iswara wrote:
> Why do Get_Line skipped the input? I have the following code:
> 
>     -- late declaration of Key words string array
>     declare
>        type Kw_Array is array (1 .. Kw_Numbers) of String (1 .. 10);
>        Key_Words : Kw_Array;
>        type W_Len_Array is array (1 .. Kw_Numbers) of Natural;
>        W_Len, Multiplier : W_Len_Array;
> 
>     begin
>        Ada.Text_IO.Put_Line ("Enter keywords less than 10 characters.");
>        for i in 1 .. Kw_Numbers loop
>           Ada.Text_IO.Put ("Keywords number ");
>           Ada.Integer_Text_IO.Put (i, 1);
>           Ada.Text_IO.Put (" = ");
> +         Ada.Text_IO.Get_Line (Key_Words (i), W_Len (i));
>  >         Ada.Text_IO.Put("Enter multiplier for keyword ");
>  >         Ada.Integer_Text_IO.Get(Multiplier(i),1);


Integer_Text_IO.Get does not read the /whole/ line that contains the 
multiplier -- it only reads the multiplier, but not the "end of line".
Insert this to skip (ignore) the rest of that input line and advance to 
the start of the next input line (which will hold the next keyword):

             Ada.Text_IO.Skip_Line;

>           Ada.Text_IO.New_Line;
>        end loop;
>     end;


As it was, because Integer_Text_IO.Get left the input pointer on the 
multiplier line, the next Get_Line read an empty next keyword (or 
whatever you typed on the multiplier line /after/ the multiplier 
digits), without needing more user input. Skip_Line should correct that.

^ permalink raw reply	[relevance 0%]

* Get_Line skip input
@ 2021-08-26  5:36  5% Richard Iswara
  2021-08-26  7:56  0% ` Niklas Holsti
  2021-08-26  9:09  3% ` Jeffrey R. Carter
  0 siblings, 2 replies; 200+ results
From: Richard Iswara @ 2021-08-26  5:36 UTC (permalink / raw)


Why do Get_Line skipped the input? I have the following code:

    -- late declaration of Key words string array
    declare
       type Kw_Array is array (1 .. Kw_Numbers) of String (1 .. 10);
       Key_Words : Kw_Array;
       type W_Len_Array is array (1 .. Kw_Numbers) of Natural;
       W_Len, Multiplier : W_Len_Array;

    begin
       Ada.Text_IO.Put_Line ("Enter keywords less than 10 characters.");
       for i in 1 .. Kw_Numbers loop
          Ada.Text_IO.Put ("Keywords number ");
          Ada.Integer_Text_IO.Put (i, 1);
          Ada.Text_IO.Put (" = ");
+         Ada.Text_IO.Get_Line (Key_Words (i), W_Len (i));
 >         Ada.Text_IO.Put("Enter multiplier for keyword ");
 >         Ada.Integer_Text_IO.Get(Multiplier(i),1);
          Ada.Text_IO.New_Line;
       end loop;
    end;

Before I put the two lines marked above, the executable only skipped the 
first instance of keyword entry.
After I put those two lines, the executable completely skipped the 
Get_Line part.
So on the terminal it shows like this:
Keywords number 1 =  Enter Multiplier for keyword <here cursor wait for 
entry>
Keywords number 2 =  Enter Multiplier for keyword <here cursor wait for 
entry>

If I modifies the line marked + into Get (Key_Words (i) (1..W_Len(i))) 
the compiler complain I did not assign W_Len. Most likely I get the 
syntax incorrect.

What do I do wrong on the original code?

^ permalink raw reply	[relevance 5%]

* Constraint error overflow
@ 2021-04-27 14:04  6% Richard Iswara
  0 siblings, 0 replies; 200+ results
From: Richard Iswara @ 2021-04-27 14:04 UTC (permalink / raw)


Ada beginner here. I was trying to multiply the first 100 integer and GNAT throw me a constraint error, overflow. I check the error was on integer 13. So what did I do wrong here?
Gnat CE 2020, Windows 10 Pro 64bit.
Here is the relevant program:

with Ada.Text_IO;
with Ada.Integer_Text_IO;

procedure Simple is
   sum : Natural := 0;
   mul : Natural := 1;

begin
   Ada.Text_IO.Put ( "Sum of first 100 integer is :" );
   Summing:
   for I in 1 .. 100 loop
      sum := sum + I;
   end loop Summing;
   Ada.Integer_Text_IO.Put ( sum );
   Ada.Text_IO.New_Line;

   Ada.Text_IO.Put ( "Multiple of the first 100 integer is :" );
   Ada.Text_IO.New_Line;
   Multiplying:
   for J in 1 .. 100 loop
      Ada.Integer_Text_IO.Put (J);
      Ada.Text_IO.New_Line;
      mul := mul * J;
   end loop Multiplying;
   Ada.Integer_Text_IO.Put ( mul );
   Ada.Text_IO.New_Line;
end Simple;


^ permalink raw reply	[relevance 6%]

* compiler confusion, overloading and "subtype mark required in this context"
@ 2021-02-07  9:15  2% Mehdi Saada
  0 siblings, 0 replies; 200+ results
From: Mehdi Saada @ 2021-02-07  9:15 UTC (permalink / raw)


In an exo to build a rational integers package, I'm having the surprise to get a heapload of "context requires function call, found procedure name". While there is no procedure of these names.

   function "+" (R1: T_rational; R2: T_rational) return T_rational is
     (if (denom(R1) = denom(R2)) then (ENUM(R1) + ENUM(r2))/ denom(R1)
      else (DENOM(R2)*ENUM(R1) + denom(r1)*ENUM(r2))/DENOM(R1)*denom(R2));

   function denom (fraction: T_rational) return Positive is (fraction.denom);
   function enum (fraction: T_rational) return Natural is (fraction.ENUM);

with usually a "no candidate interpretations match the actuals:" for the same stuff. There are several overloaded operators, but each time with different profiles so I'm very surprised it could cause trouble.

Another kind of oddity: several
 function "+" (R1: T_rational; R2: T_rational) return T_rational is
     (if (denom(R1) = denom(R2)) then (ENUM(R1) + ENUM(r2))/ denom(R1)
      else (DENOM(R2)*ENUM(R1) + denom(r1)*ENUM(r2))/DENOM(R1)*denom(R2));
cause "ambiguous expression (cannot resolve "+")" with "possible interpretation". -- here it picks
function "+" (R1: T_rational; R2: T_rational) return T_rational;
as an interpretation, which is bullocks since obviously I'm calling on Integer operations, between enum() and denom(), integer and natural, then calling on the constructor "/" who is the only "/" with the specific profile
   function "/" (N: Integer; D: Integer) return T_rational;

additional questions. I already looked up the rm. is there an attribute to 'min/'max integer without the sign (I "abs"ed them) ?

Last one:

The commented lines:
 function Get_Line return T_rational is
      use ada.Integer_Text_IO;
   begin
      loop
         declare
            S: string := Get_Line;
            Enume: integer;
            Denomi: Positive; ---- ##########
            Ind : Natural range 0..1 := 0;
            sign : T_SIGN := Positive;
            Last: Positive;
         begin
            if S(1) = '-' then SIGN := negative; ind := 0; end if;
            Get(S(s'First+ind..s'Last), Enume, Last);
            if last = S'Last then return (IF SIGN = NEGATIVE => -Enume/1 else ENUMe/1); ----------######

Both last ones are "subtype mark required in this context" while he's refering to:    type T_SIGN is (positive,negative);
But how can there be confusion ?

Thanks. this exo is suprisingly taxing... the numbers of details that go wrong !

^ permalink raw reply	[relevance 2%]

* Re: CONSTRAINT ERROR: erroneous memory access
  2020-06-06 23:40  3% CONSTRAINT ERROR: erroneous memory access jcupak
@ 2020-06-07 15:53  0% ` Anh Vo
  0 siblings, 0 replies; 200+ results
From: Anh Vo @ 2020-06-07 15:53 UTC (permalink / raw)


On Saturday, June 6, 2020 at 4:40:04 PM UTC-7, jcu...@gmail.com wrote:
> It has been a few years since I have written Ada; I used and taught Ada 95 back when I was working for a defense contractor. But, now that I'm retired, I wanted to get up to speed with Ada 2012, so I decided to implement a main program to see how the Shortest_Paths generic package works (taken from A.18.31, pages 574-576). But, when I read in the data and call the Shortest_Path function, it returns with CONSTRAINT ERROR: erroneous memory access. I've tried multiple times, but can't seem to figure out what I'm doing (or NOT doing) wrong. 
> 
> Here's the main program:
> 
> with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
> with Ada.Float_Text_IO;   use Ada.Float_Text_IO;
> with Ada.Text_IO;         use Ada.Text_IO;
> with Shortest_Paths;
> with Ada.Command_Line;    use Ada.Command_Line;
> with DirectedEdge;        use DirectedEdge;
> with Ada.Containers;      use Ada.Containers;
> with Ada.Exceptions;
> 
> procedure Main_Test is
> 
>    Input_File : Ada.Text_IO.File_Type;
> 
>    Vertices   : Integer; -- Number of nodes
>    Edges      : Integer; -- Number of paths
> 
>    Tail       : Integer; -- Node From
>    Head       : Integer; -- Node To
>    Weight     : Float;   -- Path Weight/Distance/Cost
> 
>    -- Instantiate Shortest Paths package with 0..Integer'Last subtype
>    package SP is new Shortest_Paths(Node => Natural);
>    
>    -- Use Edge'Read to read the Edge components into Item
>    
>    -- Display directed edge components
>    procedure Display(Edge : in SP.Edge) is
>    begin
>       Put(Edge.From, Width=>1); Put("->");
>       Put(Edge.To,   Width=>1); Put(" ");
>       Put(Float(Edge.Length), Fore => 0, Aft => 2, Exp => 0); Put(" ");
>    end Display;
> 
>    -- Display directed edge components at cursor
>    -- Replace List'Write with Display
>    procedure Display(Cursor: in SP.Adjacency_Lists.Cursor)
>    is
>       Edge : SP.Edge := SP.Adjacency_Lists.Element(Cursor);
>    begin
>       Display(Edge); -- Let other procedure do all the work
>    end Display;
> 
> begin
> 
> -- Open input file using arg 1
>    Open (File => Input_File,
>          Mode => In_File,
>          Name => Argument(1)); -- ../tinyEWD.txt
> 
>    Set_Input(Input_File);        -- Redirect input
>    New_Line;
>    Put("Processing '"); Put(Argument(1)); Put_Line("'");
> 
>    -- Read number of nodes (vertices)
>    Get(Vertices); New_Line;
>    Put("Vertices: ");Put(Vertices, width=>2);New_Line;
> 
>    -- Read number of paths (edges)
>    Get(Edges);
>    Put("Edges:    ");Put(Edges, Width=>2);New_Line(2);
> 
>    declare
>    
>       -- Constrain Vertex to zero-based subrange
>       subtype Vertex is Natural range 0..Vertices-1;
>       
>       -- Adj is DLL of Adjacency Lists for each Vertex
>       Adj    : array (Vertex) of SP.Adjacency_Lists.List;
>       
>       -- Edge is a record of Tail, Head, and Weight components
>       Edge   : SP.Edge;
>    
>    begin
>    
>       Put_Line("Creating Adjacency Lists"); New_Line;
>    
>       -- For each node, create empty list of adjacent nodes
>       Create_Empty_Adjacency_Lists: for Node in Vertex loop
>       
>          -- Initialize each adjacency list to empty
>          Adj(Node) := SP.Adjacency_Lists.Empty_List;
>       
>       end loop Create_Empty_Adjacency_Lists;
>    
>       -- Display and append new edge to adjacency list for node
>       -- Constrain Edge index to natural subrange
>       Append_New_Edge: for E in 0..Edges-1 loop
>       
>          Put("Edge:     ");Put(E, Width=>2);Put(" ");
>       
>          -- Get edge components from data file
>          Get(Tail);   -- Tail
>          Get(Head);   -- Head
>          Get(Weight); -- Distance/Weight
>       
>          -- Set edge components
>          Edge.From   := Tail;
>          Edge.To     := Head;
>          Edge.Length := SP.Distance(Weight);
>       
>          -- Display Edge
>          Display(Edge);
>          Put(" Appended to edge ");Put(Tail,1);
>          New_Line;
>       
>          -- Append new edge to From adjacency list
>          -- Indicating path to another node
>          Adj(Edge.From).Append(Edge);
>       
>       end loop Append_New_Edge;
>       New_Line;
>    
>       Close(Input_File);
>       Set_Input(Standard_Input); -- Reset input source
>    
>       Put_Line("Node Adjacency Lists");
>    
>       -- Display contents of each adjacency list
>       Display_Adjacency_Lists: for Node in Vertex loop
>       
>          Put("Adj[");Put(Node, Width=>1);Put("] ");
>       
>          declare
>             Edges  : Ada.Containers.Count_Type;
>          begin
>          
>             -- How many edges are in this node?
>             Edges := SP.Adjacency_Lists.Length(Adj(Node));
>             Put(Integer(Edges), Width => 1);
>             if (Edges > 1) then
>                Put(" Edges: ");
>             else
>                Put(" Edge:  ");
>             end if;
>          
>             -- Iterate over all nodes in this adjacency list
>             -- and Display each edge for each node
>             SP.Adjacency_Lists.Iterate(Adj(Node), Process => Display'Access);
>          
>          end;
>          New_Line;
>       
>       end loop Display_Adjacency_Lists;
>       New_Line;
>    
>       -- Create Edge-Weighted Graph of Node and Adjacency List
>       declare
>          EWG    : SP.Graphs.Vector; -- Edge Weighted Graphs
>          Path   : SP.Paths.List;    -- Shortest Path
>       begin
>       
>          Put_Line("Creating Edge-Weighted Graphs.");
>          EWG := SP.Graphs.Empty_Vector;
>          Put_Line("EWG Empty_Vector created.");
>          
>          Put("Initializing Shortest Path to empty list...");
>          Path := SP.Paths.Empty_List;
>          Put_Line("done.");
>          
>          for Vertex in 0..Vertices-1 loop
>             Put("Vertex: ");Put(Vertex, Width => 1);
>             EWG.Append(Adj(Vertex));
>             Put_Line(" appended to EWG.");
>          end loop;
>          New_Line;
>          
>          Put("EWG.Length = "); Put(Integer(EWG.Length), Width => 1);New_Line;
>       
>          Put_Line("Finding shortest path from node 0 to node 6");
>          declare
>             use Ada.Exceptions;
>          begin
>             -- Compute Shortest Path
>             Path := SP.Shortest_Path
>                (EWG, Source => 0, Target => 6);
>             exception
>                when Error: others =>
>                   New_Line;
>                   Put_Line(Exception_Name(Error));
>                   Put_Line(Exception_Message(Error));
>                   New_Line;
>                   Return;
>          end;
>       
>          Put("The Shortest Path from Node 0 to Node 6 ");
>          Put("contains "); Put(Integer(Path.Length)); Put(" entries.");
>          -- Display path
>       end;
>    
>    
>    end;
> 
> end Main_Test;
> 
> And here's the test data (taken from Algorithms, by Sedwick):
> 
> 8
> 15
> 4 5 0.35
> 5 4 0.35
> 4 7 0.37
> 5 7 0.28
> 7 5 0.28
> 5 1 0.32
> 0 4 0.38
> 0 2 0.26
> 7 3 0.39
> 1 3 0.29
> 2 7 0.34
> 6 2 0.40
> 3 6 0.52
> 6 0 0.58
> 6 4 0.93

It is hard to comment without Ada units Shortest_Path and DirectedEdge posted. In other word, your code does not compile.

Anh Vo 

^ permalink raw reply	[relevance 0%]

* CONSTRAINT ERROR: erroneous memory access
@ 2020-06-06 23:40  3% jcupak
  2020-06-07 15:53  0% ` Anh Vo
  0 siblings, 1 reply; 200+ results
From: jcupak @ 2020-06-06 23:40 UTC (permalink / raw)


It has been a few years since I have written Ada; I used and taught Ada 95 back when I was working for a defense contractor. But, now that I'm retired, I wanted to get up to speed with Ada 2012, so I decided to implement a main program to see how the Shortest_Paths generic package works (taken from A.18.31, pages 574-576). But, when I read in the data and call the Shortest_Path function, it returns with CONSTRAINT ERROR: erroneous memory access. I've tried multiple times, but can't seem to figure out what I'm doing (or NOT doing) wrong. 

Here's the main program:

with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Float_Text_IO;   use Ada.Float_Text_IO;
with Ada.Text_IO;         use Ada.Text_IO;
with Shortest_Paths;
with Ada.Command_Line;    use Ada.Command_Line;
with DirectedEdge;        use DirectedEdge;
with Ada.Containers;      use Ada.Containers;
with Ada.Exceptions;

procedure Main_Test is

   Input_File : Ada.Text_IO.File_Type;

   Vertices   : Integer; -- Number of nodes
   Edges      : Integer; -- Number of paths

   Tail       : Integer; -- Node From
   Head       : Integer; -- Node To
   Weight     : Float;   -- Path Weight/Distance/Cost

   -- Instantiate Shortest Paths package with 0..Integer'Last subtype
   package SP is new Shortest_Paths(Node => Natural);
   
   -- Use Edge'Read to read the Edge components into Item
   
   -- Display directed edge components
   procedure Display(Edge : in SP.Edge) is
   begin
      Put(Edge.From, Width=>1); Put("->");
      Put(Edge.To,   Width=>1); Put(" ");
      Put(Float(Edge.Length), Fore => 0, Aft => 2, Exp => 0); Put(" ");
   end Display;

   -- Display directed edge components at cursor
   -- Replace List'Write with Display
   procedure Display(Cursor: in SP.Adjacency_Lists.Cursor)
   is
      Edge : SP.Edge := SP.Adjacency_Lists.Element(Cursor);
   begin
      Display(Edge); -- Let other procedure do all the work
   end Display;

begin

-- Open input file using arg 1
   Open (File => Input_File,
         Mode => In_File,
         Name => Argument(1)); -- ../tinyEWD.txt

   Set_Input(Input_File);        -- Redirect input
   New_Line;
   Put("Processing '"); Put(Argument(1)); Put_Line("'");

   -- Read number of nodes (vertices)
   Get(Vertices); New_Line;
   Put("Vertices: ");Put(Vertices, width=>2);New_Line;

   -- Read number of paths (edges)
   Get(Edges);
   Put("Edges:    ");Put(Edges, Width=>2);New_Line(2);

   declare
   
      -- Constrain Vertex to zero-based subrange
      subtype Vertex is Natural range 0..Vertices-1;
      
      -- Adj is DLL of Adjacency Lists for each Vertex
      Adj    : array (Vertex) of SP.Adjacency_Lists.List;
      
      -- Edge is a record of Tail, Head, and Weight components
      Edge   : SP.Edge;
   
   begin
   
      Put_Line("Creating Adjacency Lists"); New_Line;
   
      -- For each node, create empty list of adjacent nodes
      Create_Empty_Adjacency_Lists: for Node in Vertex loop
      
         -- Initialize each adjacency list to empty
         Adj(Node) := SP.Adjacency_Lists.Empty_List;
      
      end loop Create_Empty_Adjacency_Lists;
   
      -- Display and append new edge to adjacency list for node
      -- Constrain Edge index to natural subrange
      Append_New_Edge: for E in 0..Edges-1 loop
      
         Put("Edge:     ");Put(E, Width=>2);Put(" ");
      
         -- Get edge components from data file
         Get(Tail);   -- Tail
         Get(Head);   -- Head
         Get(Weight); -- Distance/Weight
      
         -- Set edge components
         Edge.From   := Tail;
         Edge.To     := Head;
         Edge.Length := SP.Distance(Weight);
      
         -- Display Edge
         Display(Edge);
         Put(" Appended to edge ");Put(Tail,1);
         New_Line;
      
         -- Append new edge to From adjacency list
         -- Indicating path to another node
         Adj(Edge.From).Append(Edge);
      
      end loop Append_New_Edge;
      New_Line;
   
      Close(Input_File);
      Set_Input(Standard_Input); -- Reset input source
   
      Put_Line("Node Adjacency Lists");
   
      -- Display contents of each adjacency list
      Display_Adjacency_Lists: for Node in Vertex loop
      
         Put("Adj[");Put(Node, Width=>1);Put("] ");
      
         declare
            Edges  : Ada.Containers.Count_Type;
         begin
         
            -- How many edges are in this node?
            Edges := SP.Adjacency_Lists.Length(Adj(Node));
            Put(Integer(Edges), Width => 1);
            if (Edges > 1) then
               Put(" Edges: ");
            else
               Put(" Edge:  ");
            end if;
         
            -- Iterate over all nodes in this adjacency list
            -- and Display each edge for each node
            SP.Adjacency_Lists.Iterate(Adj(Node), Process => Display'Access);
         
         end;
         New_Line;
      
      end loop Display_Adjacency_Lists;
      New_Line;
   
      -- Create Edge-Weighted Graph of Node and Adjacency List
      declare
         EWG    : SP.Graphs.Vector; -- Edge Weighted Graphs
         Path   : SP.Paths.List;    -- Shortest Path
      begin
      
         Put_Line("Creating Edge-Weighted Graphs.");
         EWG := SP.Graphs.Empty_Vector;
         Put_Line("EWG Empty_Vector created.");
         
         Put("Initializing Shortest Path to empty list...");
         Path := SP.Paths.Empty_List;
         Put_Line("done.");
         
         for Vertex in 0..Vertices-1 loop
            Put("Vertex: ");Put(Vertex, Width => 1);
            EWG.Append(Adj(Vertex));
            Put_Line(" appended to EWG.");
         end loop;
         New_Line;
         
         Put("EWG.Length = "); Put(Integer(EWG.Length), Width => 1);New_Line;
      
         Put_Line("Finding shortest path from node 0 to node 6");
         declare
            use Ada.Exceptions;
         begin
            -- Compute Shortest Path
            Path := SP.Shortest_Path
               (EWG, Source => 0, Target => 6);
            exception
               when Error: others =>
                  New_Line;
                  Put_Line(Exception_Name(Error));
                  Put_Line(Exception_Message(Error));
                  New_Line;
                  Return;
         end;
      
         Put("The Shortest Path from Node 0 to Node 6 ");
         Put("contains "); Put(Integer(Path.Length)); Put(" entries.");
         -- Display path
      end;
   
   
   end;

end Main_Test;

And here's the test data (taken from Algorithms, by Sedwick):

8
15
4 5 0.35
5 4 0.35
4 7 0.37
5 7 0.28
7 5 0.28
5 1 0.32
0 4 0.38
0 2 0.26
7 3 0.39
1 3 0.29
2 7 0.34
6 2 0.40
3 6 0.52
6 0 0.58
6 4 0.93

^ permalink raw reply	[relevance 3%]

* Re: GNAT: no visible subprogram matches the specification for "Put"
  2019-10-04 18:53  5% GNAT: no visible subprogram matches the specification for "Put" Vincent Marciante
@ 2019-10-05 10:50  0% ` Stephen Leake
  0 siblings, 0 replies; 200+ results
From: Stephen Leake @ 2019-10-05 10:50 UTC (permalink / raw)


On Friday, October 4, 2019 at 11:53:34 AM UTC-7, Vincent Marciante wrote:
> Hi all,
> 
> I think that I might be hitting a GNAT defect but am not sure.
> I already have a work-around but wanted some feedback before 
> I go through channels to submit this to Adacore (if actually 
> a defect.)  Maybe I am missing some overloading rule but I 
> think that the following should compile and run: one part that 
> appears in the middle does compile and does produce the expected
> output but the second to last unit does not compile useing a 
> GNATPRO 19 series compiler.  That place is marked with --Builder
> results.
> 
> So, should all of the following be compilable?
> 
> with Ada.Text_IO;
> 
> package Ada_Text_IO_Adaptor is
> 
>   procedure Put
>            (X    : in Integer;
>             Base : in Ada.Text_IO.Number_Base);
> 
>   procedure New_Line;
> 
> end Ada_Text_IO_Adaptor;
> 
> -------
> 
> with Ada.Integer_Text_IO;
> 
> package body Ada_Text_IO_Adaptor is
> 
>   procedure Put
>            (X    : in Integer;
>             Base : in Ada.Text_IO.Number_Base) is
>   begin
>     Ada.Integer_Text_IO.Put(Item=>X,Base=>Base);
>   end Put;
> 
>   procedure New_Line is
>   begin
>     Ada.Text_IO.New_Line;
>   end New_Line;
> 
> end Ada_Text_IO_Adaptor;
> 
> -------
> 
> generic
> 
>   type Number_Base is range <>;
>   Default_Base : Number_Base;
> 
>   with procedure Put      (X    : in Integer;
>                            Base : in Number_Base 
>                                   := Default_Base) is <>;
>   with procedure Put      (X    : in String) is <>;
>   with procedure Put_Line (X    : in String) is <>;
>   with procedure New_Line is <>;
> 
> package Signature_Package_Generic is end;
> 
> -------
> 
> with Ada.Text_IO, Ada.Integer_Text_IO, Ada_Text_IO_Adaptor;
>  use Ada.Text_IO, Ada.Integer_Text_IO, Ada_Text_IO_Adaptor;
> 
> with Signature_Package_Generic;
> 
> package Signature_Package_Instance is
>     new Signature_Package_Generic
>                          (Number_Base  => Ada.Text_IO.Number_Base,
>                           Default_Base => 10);
> 
> -------
> 
> with Signature_Package_Generic;
> generic
>   with package Instance is new Signature_Package_Generic(<>);
> procedure Signature_Package_Instance_Test_Generic;
> 
> -------
> 
> procedure Signature_Package_Instance_Test_Generic is
> begin 
>   Instance.New_Line;
>   Instance.Put_Line("Direct Instance Put_Line(""string"")");
>   Instance.Put     ("Direct Instance Put     (""string"")");
> end;
> 
> -------
> 
> with      Signature_Package_Instance;
> with      Signature_Package_Instance_Test_Generic;
> procedure Signature_Package_Instance_Test is 
>       new Signature_Package_Instance_Test_Generic
>          (Signature_Package_Instance); --compiles and runs as expected
> 
> -------
> 
> with Signature_Package_Generic;
> generic
>   with package Instance is new Signature_Package_Generic(<>);
> package Signature_Package_Reexport_Generic is
> 
>   subtype Number_Base is Instance.Number_Base;
>   Default_Base : Number_Base := Instance.Default_Base;
> 
>   procedure Put      (X    : in Integer;
>                       Base : in Number_Base
>                              := Default_Base) renames Instance. Put;
>   procedure Put      (X    : in String)       renames Instance. Put; -- instantiation error
>   procedure Put_Line (X    : in String)       renames Instance. Put_Line;
>   procedure New_Line                          renames Instance. New_Line;
> 
> end Signature_Package_Reexport_Generic;
> 
> -------
> 
> with    Signature_Package_Instance;
> with    Signature_Package_Reexport_Generic;
> package Signature_Package_Reexport_Instance is
>     new Signature_Package_Reexport_Generic
>        (Signature_Package_Instance);
> --Builder results
> --    Signature_Package_Reexport_Instance.ads
> --        108:1 instantiation error at  signature_package_reexport_generic.ads:98
> --        108:1 no visible subprogram matches the specification for "Put"
> 
> -------
> 
> with      Signature_Package_Reexport_Instance;
> procedure Signature_Package_Reexport_Test is
> begin 
>   Signature_Package_Reexport_Instance.New_Line;
>   Signature_Package_Reexport_Instance.Put_Line("Reexport Put_Line(""string"")");
>   Signature_Package_Reexport_Instance.Put     ("Reexport Put     (""string"")");
> end;

What "Put" do you think is visible at the declaration of Signature_Package_Reexport_Instance? There is no "use" clause in effect.

--  Stephe

^ permalink raw reply	[relevance 0%]

* GNAT: no visible subprogram matches the specification for "Put"
@ 2019-10-04 18:53  5% Vincent Marciante
  2019-10-05 10:50  0% ` Stephen Leake
  0 siblings, 1 reply; 200+ results
From: Vincent Marciante @ 2019-10-04 18:53 UTC (permalink / raw)


Hi all,

I think that I might be hitting a GNAT defect but am not sure.
I already have a work-around but wanted some feedback before 
I go through channels to submit this to Adacore (if actually 
a defect.)  Maybe I am missing some overloading rule but I 
think that the following should compile and run: one part that 
appears in the middle does compile and does produce the expected
output but the second to last unit does not compile useing a 
GNATPRO 19 series compiler.  That place is marked with --Builder
results.

So, should all of the following be compilable?

with Ada.Text_IO;

package Ada_Text_IO_Adaptor is

  procedure Put
           (X    : in Integer;
            Base : in Ada.Text_IO.Number_Base);

  procedure New_Line;

end Ada_Text_IO_Adaptor;

-------

with Ada.Integer_Text_IO;

package body Ada_Text_IO_Adaptor is

  procedure Put
           (X    : in Integer;
            Base : in Ada.Text_IO.Number_Base) is
  begin
    Ada.Integer_Text_IO.Put(Item=>X,Base=>Base);
  end Put;

  procedure New_Line is
  begin
    Ada.Text_IO.New_Line;
  end New_Line;

end Ada_Text_IO_Adaptor;

-------

generic

  type Number_Base is range <>;
  Default_Base : Number_Base;

  with procedure Put      (X    : in Integer;
                           Base : in Number_Base 
                                  := Default_Base) is <>;
  with procedure Put      (X    : in String) is <>;
  with procedure Put_Line (X    : in String) is <>;
  with procedure New_Line is <>;

package Signature_Package_Generic is end;

-------

with Ada.Text_IO, Ada.Integer_Text_IO, Ada_Text_IO_Adaptor;
 use Ada.Text_IO, Ada.Integer_Text_IO, Ada_Text_IO_Adaptor;

with Signature_Package_Generic;

package Signature_Package_Instance is
    new Signature_Package_Generic
                         (Number_Base  => Ada.Text_IO.Number_Base,
                          Default_Base => 10);

-------

with Signature_Package_Generic;
generic
  with package Instance is new Signature_Package_Generic(<>);
procedure Signature_Package_Instance_Test_Generic;

-------

procedure Signature_Package_Instance_Test_Generic is
begin 
  Instance.New_Line;
  Instance.Put_Line("Direct Instance Put_Line(""string"")");
  Instance.Put     ("Direct Instance Put     (""string"")");
end;

-------

with      Signature_Package_Instance;
with      Signature_Package_Instance_Test_Generic;
procedure Signature_Package_Instance_Test is 
      new Signature_Package_Instance_Test_Generic
         (Signature_Package_Instance); --compiles and runs as expected

-------

with Signature_Package_Generic;
generic
  with package Instance is new Signature_Package_Generic(<>);
package Signature_Package_Reexport_Generic is

  subtype Number_Base is Instance.Number_Base;
  Default_Base : Number_Base := Instance.Default_Base;

  procedure Put      (X    : in Integer;
                      Base : in Number_Base
                             := Default_Base) renames Instance. Put;
  procedure Put      (X    : in String)       renames Instance. Put; -- instantiation error
  procedure Put_Line (X    : in String)       renames Instance. Put_Line;
  procedure New_Line                          renames Instance. New_Line;

end Signature_Package_Reexport_Generic;

-------

with    Signature_Package_Instance;
with    Signature_Package_Reexport_Generic;
package Signature_Package_Reexport_Instance is
    new Signature_Package_Reexport_Generic
       (Signature_Package_Instance);
--Builder results
--    Signature_Package_Reexport_Instance.ads
--        108:1 instantiation error at  signature_package_reexport_generic.ads:98
--        108:1 no visible subprogram matches the specification for "Put"

-------

with      Signature_Package_Reexport_Instance;
procedure Signature_Package_Reexport_Test is
begin 
  Signature_Package_Reexport_Instance.New_Line;
  Signature_Package_Reexport_Instance.Put_Line("Reexport Put_Line(""string"")");
  Signature_Package_Reexport_Instance.Put     ("Reexport Put     (""string"")");
end;


^ permalink raw reply	[relevance 5%]

* Re: ambiguous expression (cannot resolve "Put")
  2019-07-27  7:32  5% ambiguous expression (cannot resolve "Put") cryintothebluesky
@ 2019-07-27  8:28  0% ` J-P. Rosen
  0 siblings, 0 replies; 200+ results
From: J-P. Rosen @ 2019-07-27  8:28 UTC (permalink / raw)


Le 27/07/2019 à 09:32, cryintothebluesky@gmail.com a écrit :
> Hi, could anyone suggest how to print 'Size attribute for various integers? There seems to be an issue with overloaded Put() function. Not sure why only 'Size attribute causes this issue, other attributes like 'First and 'Last seem OK. I suppose I could do something like Ada.Integer_Text_IO.Put() and Ada.Short_Integer_Text_IO.Put() but this doesn't look very nice. 
> 
> 
> with Ada.Text_IO;               use Ada.Text_IO;
> with Ada.Integer_Text_IO;       use Ada.Integer_Text_IO;
> with Ada.Short_Integer_Text_IO; use Ada.Short_Integer_Text_IO;
> 
> procedure Integer_Types is
> begin
> 	Put("Integer'Size        "); Put(Integer'Size); New_Line;
> 	Put("Integer'First       "); Put(Integer'First); New_Line;
> 	Put("Integer'Last        "); Put(Integer'Last); New_Line;
> 
> 	Put("Short_Integer'Size  "); Put(Short_Integer'Size); New_Line;
> 	Put("Short_Integer'First "); Put(Short_Integer'First); New_Line;
> 	Put("Short_Integer'Last  "); Put(Short_Integer'Last); New_Line;
> end Integer_Types;
> 

Integer'First is of type Integer; therefore overloading resolution can
resolve the Put to the one on Integer. However, Integer'Size is of type
Universal_Integer, i.e. the actual type is determined from context.
Since you have two acceptable contexts, it is ambiguous.

You can either qualifie the expression: Integer'(Integer'Size) or
specify explicitely which Put you want:
Integer_Text_IO.Put (Integer'Size);

-- 
J-P. Rosen
Adalog
2 rue du Docteur Lombard, 92441 Issy-les-Moulineaux CEDEX
Tel: +33 1 45 29 21 52, Fax: +33 1 45 29 25 00
http://www.adalog.fr

^ permalink raw reply	[relevance 0%]

* ambiguous expression (cannot resolve "Put")
@ 2019-07-27  7:32  5% cryintothebluesky
  2019-07-27  8:28  0% ` J-P. Rosen
  0 siblings, 1 reply; 200+ results
From: cryintothebluesky @ 2019-07-27  7:32 UTC (permalink / raw)


Hi, could anyone suggest how to print 'Size attribute for various integers? There seems to be an issue with overloaded Put() function. Not sure why only 'Size attribute causes this issue, other attributes like 'First and 'Last seem OK. I suppose I could do something like Ada.Integer_Text_IO.Put() and Ada.Short_Integer_Text_IO.Put() but this doesn't look very nice. 


with Ada.Text_IO;               use Ada.Text_IO;
with Ada.Integer_Text_IO;       use Ada.Integer_Text_IO;
with Ada.Short_Integer_Text_IO; use Ada.Short_Integer_Text_IO;

procedure Integer_Types is
begin
	Put("Integer'Size        "); Put(Integer'Size); New_Line;
	Put("Integer'First       "); Put(Integer'First); New_Line;
	Put("Integer'Last        "); Put(Integer'Last); New_Line;

	Put("Short_Integer'Size  "); Put(Short_Integer'Size); New_Line;
	Put("Short_Integer'First "); Put(Short_Integer'First); New_Line;
	Put("Short_Integer'Last  "); Put(Short_Integer'Last); New_Line;
end Integer_Types;


Compile
   [Ada]          integer_types.adb
integer_types.adb:13:38: ambiguous expression (cannot resolve "Put")
integer_types.adb:13:38: possible interpretation at a-tiinio.ads:66, instance at a-siteio.ads:18
integer_types.adb:13:38: possible interpretation at a-tiinio.ads:66, instance at a-inteio.ads:18
integer_types.adb:17:38: ambiguous expression (cannot resolve "Put")
integer_types.adb:17:38: possible interpretation at a-tiinio.ads:66, instance at a-siteio.ads:18
integer_types.adb:17:38: possible interpretation at a-tiinio.ads:66, instance at a-inteio.ads:18
gprbuild: *** compilation phase failed

^ permalink raw reply	[relevance 5%]

* Re: Memory pools
    2018-05-31 19:28  4% ` gorgelo
@ 2018-05-31 19:33  3% ` gorgelo
  1 sibling, 0 replies; 200+ results
From: gorgelo @ 2018-05-31 19:33 UTC (permalink / raw)


And to follow up on the naive benchmarks:
https://github.com/frol/completely-unscientific-benchmarks

Using the memory pool in the previous post it can be used to implement the Treap algorithm (after some minor modifications):

pragma Suppress (Tampering_Check);
-- Tampering checks are only for multi-task applications.
-- Since this application is single task we can safely
-- suppress tampering checks of the standard containers.
-- If performance is an issue, the Ada-Traits Containers may be used instead.

with System.Storage_Elements;
with System.Storage_Pools;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Containers.Vectors;
with Ada.Unchecked_Deallocation;
with Ada.Numerics.Discrete_Random;

procedure Main is

   subtype Storage_Offset is System.Storage_Elements.Storage_Offset;
   subtype Storage_Count  is System.Storage_Elements.Storage_Count;
   subtype Storage_Array  is System.Storage_Elements.Storage_Array;

   subtype Root_Storage_Pool is System.Storage_Pools.Root_Storage_Pool;

   subtype Integer_Address is System.Storage_Elements.Integer_Address;

   subtype Count_Type is Ada.Containers.Count_Type;

   use type Count_Type;
   use type Storage_Offset;
   use type Integer_Address;

   procedure Put (Text : String) renames Ada.Text_IO.Put;

   procedure Put_Line (Text : String) renames Ada.Text_IO.Put_Line;

   procedure Put_Line (I : Integer) is
   begin
      Ada.Integer_Text_IO.Put (I, 0);
      Ada.Text_IO.New_Line;
   end Put_Line;

   procedure Put (I : Integer) is
   begin
      Ada.Integer_Text_IO.Put (I, 0);
   end Put;

   procedure Put (I : Storage_Offset) is
   begin
      Ada.Integer_Text_IO.Put (Integer (I), 0);
   end Put;

   function To_Integer (Value : System.Address) return Integer_Address
                        renames System.Storage_Elements.To_Integer;

   generic
      Slot_Size : Positive;
      -- Specifies the size of each slot in Storage Elements (bytes)
      -- Must be big enough to store any object one wishes to allocate
      -- inside the memory pool.

      MAX : Positive;
      -- Specifies the number of slots that will be allocated in an array
      -- from the heap every time more memory needs to be pre-allocated.

   package Arena_Pools is

      type Arena (<>) is new Root_Storage_Pool with private;

      function Make return Arena;

      overriding
      procedure Allocate
        (  Pool      : in out Arena;
           Address   : out System.Address;
           Size      : Storage_Count;
           Alignment : Storage_Count
          );

      overriding
      procedure Deallocate
        (  Pool      : in out Arena;
           Address   : System.Address;
           Size      : Storage_Count;
           Alignment : Storage_Count
          );

      overriding
      function Storage_Size (Pool : Arena) return Storage_Count;
      -- Approximation of how many Storage Elements (bytes)
      -- have been heap-allocated.

   private

      type Slot is record
         Elements : Storage_Array (1..Storage_Offset (Slot_Size));
      end record;

      subtype Slot_Index is Storage_Offset range 1.. Storage_Offset (MAX);

      type Slots_Array is array (Slot_Index) of Slot;

      subtype Free_Index is Integer range 1..MAX;
      -- This Integer type (32-bits) is created in order to not use the type
      -- Storage_Offset (64-bits) in the free indices vector.

      package Indices_Vector is new Ada.Containers.Vectors
        (Index_Type   => Positive,
         Element_Type => Free_Index,
         "="          => "=");

      type Slots_Envelope is record
         Items        : Slots_Array;
         Free_Indices : Indices_Vector.Vector;
      end record;

      type Slots_Envelope_Ptr is access all Slots_Envelope;

      package Envelope_Vectors is new Ada.Containers.Vectors
        (Index_Type   => Positive,
         Element_Type => Slots_Envelope_Ptr,
         "="          => "=");

      type Arena is new Root_Storage_Pool with record
         Index : Positive := 1;
         -- Indicates which array of slots to first search for a free index

         Envelopes : Envelope_Vectors.Vector;
      end record;

      overriding
      procedure Finalize (This : in out Arena);
      -- Deallocates all allocated memory from the heap

   end Arena_Pools;

   package body Arena_Pools is

      function Make return Slots_Envelope_Ptr is
         Envelope : Slots_Envelope_Ptr := new Slots_Envelope;
      begin
         Envelope.Free_Indices.Reserve_Capacity (Ada.Containers.Count_Type (MAX));
         for I in Slot_Index'Range loop
            Envelope.Free_Indices.Append (Free_Index (I));
         end loop;

         return Envelope;
      end Make;

      function Make return Arena is
         Envelope : Slots_Envelope_Ptr := Make;
      begin
         return This : Arena do
            This.Envelopes.Append (Envelope);
         end return;
      end Make;

      function Determine_Index (Pool    : Arena;
                                Address : System.Address) return Positive is
         Searched_For : Natural := 0;
         First_Address : System.Address;
         Last_Address  : System.Address;
      begin
         for I in Pool.Envelopes.First_Index..Pool.Envelopes.Last_Index loop
            First_Address := Pool.Envelopes (I).Items (1)'Address;
            Last_Address  := Pool.Envelopes (I).Items (Storage_Offset (MAX))'Address;
            if
              To_Integer (First_Address) <= To_Integer (Address) and
              To_Integer (Address)       <= To_Integer (Last_Address)
            then
               Searched_For := I;
               exit;
            end if;
         end loop;

         if Searched_For = 0 then
            raise Storage_Error;
         end if;

         return Searched_For;
      end Determine_Index;

      procedure Allocate
        (Pool      : in out Arena;
         Address   : out System.Address;
         Size      : Storage_Count;
         Alignment : Storage_Count)
      is
         Id : Slot_Index;
      begin
         if Pool.Envelopes (Pool.Index).Free_Indices.Length > 0 then
            Id := Slot_Index (Pool.Envelopes (Pool.Index).Free_Indices.Last_Element);
            Pool.Envelopes (Pool.Index).Free_Indices.Delete_Last;
         else
            declare
               Has_Found : Boolean := False;
            begin
               for I in Pool.Envelopes.First_Index .. Pool.Envelopes.Last_Index loop
                  if Pool.Envelopes (I).Free_Indices.Length > 0 then
                     Pool.Index := I;
                     Id := Slot_Index (Pool.Envelopes (Pool.Index).Free_Indices.Last_Element);
                     Pool.Envelopes (Pool.Index).Free_Indices.Delete_Last;
                     Has_Found := True;
                     exit;
                  end if;
               end loop;

               if not Has_Found then
                  declare
                     E : Slots_Envelope_Ptr := Make;
                  begin
                     Pool.Envelopes.Append (E);
                     Pool.Index := Pool.Envelopes.Last_Index;
                     Id := Slot_Index (Pool.Envelopes (Pool.Index).Free_Indices.Last_Element);
                     Pool.Envelopes (Pool.Index).Free_Indices.Delete_Last;
                  end;
               end if;
            end;
         end if;

         Address := Pool.Envelopes (Pool.Index).Items (Id).Elements'Address;
      end Allocate;

      procedure Deallocate (Pool      : in out Arena;
                            Address   : System.Address;
                            Size      : Storage_Count;
                            Alignment : Storage_Count)
      is
         I : constant Positive := Determine_Index (Pool, Address);

         First_Address : System.Address;
         Last_Address  : System.Address;

         Slot_Id : Slot_Index;

         D : Integer_Address;
      begin
         First_Address := Pool.Envelopes (I).Items (1)'Address;
         Last_Address  := Pool.Envelopes (I).Items (Storage_Offset (MAX))'Address;

         D := (To_Integer (Last_Address) - To_Integer (First_Address) + Integer_Address (Slot_Size)) / Integer_Address (MAX);

         Slot_Id := Slot_Index ((To_Integer (Address) + Integer_Address (Slot_Size) - To_Integer (First_Address))/ D);

         Pool.Envelopes (I).Free_Indices.Append (Free_Index (Slot_Id));
      end Deallocate;

      function Storage_Size (Pool : Arena) return Storage_Count is
         Result : Storage_Count := 0;
      begin
         for Envelope of Pool.Envelopes loop
            Result := Storage_Count (Slot_Size*MAX) + Storage_Count (Envelope.Free_Indices.Capacity * 4);
         end loop;

         return Result;
      end Storage_Size;

      procedure Free is new Ada.Unchecked_Deallocation (Object => Slots_Envelope,
                                                        Name   => Slots_Envelope_Ptr);

      procedure Finalize (This : in out Arena) is
      begin
         for Envelope of This.Envelopes loop
            Free (Envelope);
         end loop;
         This.Envelopes.Clear;
      end Finalize;

   end Arena_Pools;

   package Pools is new Arena_Pools (24, 200_000);

   Pool : Pools.Arena := Pools.Make;

   -- Here ends the definition of the Storage pool and here begins
   -- implementation of the algorithm.

   package Integer_Random is new Ada.Numerics.Discrete_Random (Integer);

   G : Integer_Random.Generator;

   type Node;
   type Node_Ptr is access all Node with
     Storage_Pool => Pool;

   type Node is record
      Left  : Node_Ptr;
      Right : Node_Ptr;
      X     : Integer := 0;
      Y     : Integer := Integer_Random.Random (G);
   end record with
     Size => 24*8;

   package Tree_Def is

      type Tree is tagged private;

      function Has_Value (T : in out Tree;
                          X : in     Integer) return Boolean;

      procedure Insert (T : in out Tree;
                        X : in     Integer);

      procedure Erase (T : in out Tree;
                       X : in     Integer);

   private

      function Merge (Lower   : Node_Ptr;
                      Greater : Node_Ptr) return Node_Ptr;

      function Merge (Lower   : Node_Ptr;
                      Equal   : Node_Ptr;
                      Greater : Node_Ptr) return Node_Ptr;

      procedure Split (Orig             : in     Node_Ptr;
                       Lower            : in out Node_Ptr;
                       Greater_Or_Equal : in out Node_Ptr;
                       Value            : in     Integer);

      procedure Split (Orig    : in     Node_Ptr;
                       Lower   : in out Node_Ptr;
                       Equal   : in out Node_Ptr;
                       Greater : in out Node_Ptr;
                       Value   : in     Integer);

      procedure Make_Node (Node :    out Node_Ptr;
                           X    : in     Integer);

      type Tree is tagged record
         Root: Node_Ptr := null;
      end record;

   end Tree_Def;

   package body Tree_Def is

      procedure Free is new Ada.Unchecked_Deallocation(Object => Node,
                                                       Name   => Node_Ptr);

      procedure Make_Node (Node :    out Node_Ptr;
                           X    : in     Integer) is
      begin
         Node := new Main.Node;
         Node.X := X;
         Node.Y := Integer_Random.Random (G);
      end Make_Node;

      procedure Delete_Node (Node : in out Node_Ptr) is
      begin
         if Node /= null then
            if Node.Left /= null then
               Delete_Node(Node.Left);
            end if;

            if Node.Right /= null then
               Delete_Node (Node.Right);
            end if;

            Free (Node);
         end if;
      end Delete_Node;

      function Merge (Lower   : Node_Ptr;
                      Greater : Node_Ptr) return Node_Ptr is
      begin
         if Lower = null then
            return Greater;
         end if;

         if Greater = null then
            return lower;
         end if;

         if Lower.Y < Greater.Y then
            Lower.Right := Merge (Lower.Right, Greater);
            return Lower;
         else
            Greater.Left := Merge (Lower, Greater.Left);
            return Greater;
         end if;
      end Merge;

      function Merge (Lower   : Node_Ptr;
                      Equal   : Node_Ptr;
                      Greater : Node_Ptr) return Node_Ptr is
      begin
         return Merge (Merge (Lower, Equal), Greater);
      end merge;

      procedure Split (Orig             : in     Node_Ptr;
                       Lower            : in out Node_Ptr;
                       Greater_Or_Equal : in out Node_Ptr;
                       Value            : in     Integer) is
      begin
         if Orig = null then
            Lower := null;
            Greater_Or_Equal := null;
            return;
         end if;
         if Orig.X < Value then
            Lower := Orig;
            Split (Lower.Right, Lower.Right, Greater_Or_Equal, Value);
         else
            Greater_Or_Equal := Orig;
            Split (Greater_Or_Equal.Left, Lower, Greater_Or_Equal.Left, Value);
         end if;
      end Split;

      procedure Split (Orig    : in     Node_Ptr;
                       Lower   : in out Node_Ptr;
                       Equal   : in out Node_Ptr;
                       Greater : in out Node_Ptr;
                       Value   : in     Integer)
      is
         Equal_Or_Greater: Node_Ptr;
      begin
         Split (Orig, Lower, Equal_Or_Greater, Value);
         Split (Equal_Or_Greater, Equal, Greater, Value + 1);
      end Split;

      function Has_Value (T : in out Tree;
                          X : in     Integer) return Boolean
      is
         Lower   : Node_Ptr;
         Equal   : Node_Ptr;
         Greater : Node_Ptr;

         Result : Boolean;
      begin
         Split (T.Root, Lower, Equal, Greater, X);
         Result := Equal /= null;
         T.Root := Merge (Lower, Equal, Greater);
         return Result;
      end Has_Value;

      procedure Insert (T : in out Tree;
                        X : in     Integer)
      is
         Lower   : Node_Ptr;
         Equal   : Node_Ptr;
         Greater : Node_Ptr;
      begin
         Split (T.Root, Lower, Equal, Greater, X);
         if Equal = null then
            Make_Node (Equal, X);
         end if;
         T.Root := Merge (Lower, Equal, Greater);
      end Insert;

      procedure Erase (T : in out Tree;
                       X : in     Integer) is
         Lower   : Node_Ptr;
         Equal   : Node_Ptr;
         Greater : Node_Ptr;
      begin
         Split (T.Root, Lower, Equal, Greater, X);
         T.Root := Merge (Lower, Greater);
         -- commenting out the following line
         -- doesn't seem to affect running time by much, if at all
         Delete_Node (Equal);
      end Erase;

   end Tree_Def;

   Tree    : Tree_Def.Tree;
   Current : Integer := 5;
   Result  : Integer := 0;
   Mode    : Integer;

begin
   Integer_Random.Reset (G);

   for I in 1..1_000_000 loop
      Mode := I mod 3;
      Current := (Current * 57 + 43) mod 10007;
      if Mode = 0 then
         Tree.Insert (Current);
      elsif Mode = 1 then
         Tree.Erase (Current);
      else
         Result := Result + (if Tree.Has_Value (Current) then 1 else 0);
      end if;
   end loop;
   Put_Line (Result);

end Main;

^ permalink raw reply	[relevance 3%]

* Re: Memory pools
  @ 2018-05-31 19:28  4% ` gorgelo
  2018-05-31 19:33  3% ` gorgelo
  1 sibling, 0 replies; 200+ results
From: gorgelo @ 2018-05-31 19:28 UTC (permalink / raw)


Here is an example of an unbounded storage pool that handles deallocations and is used for allocating 3 Integers inside it and then deallocating them:

with System.Storage_Elements;
with System.Storage_Pools;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Containers.Vectors;
with Ada.Unchecked_Deallocation;

procedure Main is

   subtype Storage_Offset is System.Storage_Elements.Storage_Offset;
   subtype Storage_Count  is System.Storage_Elements.Storage_Count;
   subtype Storage_Array  is System.Storage_Elements.Storage_Array;

   subtype Root_Storage_Pool is System.Storage_Pools.Root_Storage_Pool;

   subtype Integer_Address is System.Storage_Elements.Integer_Address;

   use type Ada.Containers.Count_Type;
   use type Storage_Offset;
   use type Integer_Address;

   procedure Put (Text : String) renames Ada.Text_IO.Put;

   procedure Put_Line (Text : String) renames Ada.Text_IO.Put_Line;

   procedure Put_Line (I : Integer) is
   begin
      Ada.Integer_Text_IO.Put (I);
      Ada.Text_IO.New_Line;
   end Put_Line;

   procedure Put (I : Integer) is
   begin
      Ada.Integer_Text_IO.Put (I, 0);
   end Put;

   procedure Put (I : Storage_Offset) is
   begin
      Ada.Integer_Text_IO.Put (Integer (I), 0);
   end Put;

   function To_Integer (Value : System.Address) return Integer_Address
                        renames System.Storage_Elements.To_Integer;

   package Arena_Pools is

      type Arena (<>) is new Root_Storage_Pool with private;

      function Make return Arena;

      overriding
      procedure Allocate
        (  Pool      : in out Arena;
           Address   : out System.Address;
           Size      : Storage_Count;
           Alignment : Storage_Count
          );

      overriding
      procedure Deallocate
        (  Pool      : in out Arena;
           Address   : System.Address;
           Size      : Storage_Count;
           Alignment : Storage_Count
          );

      overriding
      function Storage_Size (Pool : Arena) return Storage_Count;
      -- Approximation of how many Storage Elements (bytes)
      -- have been heap-allocated.

   private

      Slot_Size : constant := 20;
      -- Specifies the size of each slot in Storage Elements (bytes)
      -- Must be big enough to store any object one wishes to allocate
      -- inside the memory pool.

      type Slot is record
         Elements : Storage_Array (1..Slot_Size);
      end record;

      MAX : constant := 200_000;
      -- Specifies the number of slots that will be allocated in an array
      -- from the heap every time more memory needs to be pre-allocated.

      subtype Slot_Index is Storage_Offset range 1..MAX;

      type Slots_Array is array (Slot_Index) of Slot;

      subtype Free_Index is Integer range 1..MAX;
      -- This Integer type (32-bits) is created in order to not use the type
      -- Storage_Offset (64-bits) in the free indices vector.

      package Indices_Vector is new Ada.Containers.Vectors
        (Index_Type   => Positive,
         Element_Type => Free_Index,
         "="          => "=");

      type Slots_Envelope is record
         Items        : Slots_Array;
         Free_Indices : Indices_Vector.Vector;
      end record;

      type Slots_Envelope_Ptr is access all Slots_Envelope;

      package Envelope_Vectors is new Ada.Containers.Vectors
        (Index_Type   => Positive,
         Element_Type => Slots_Envelope_Ptr,
         "="          => "=");

      type Arena is new Root_Storage_Pool with record
         Index : Positive := 1;
         -- Indicates which array of slots to first search for a free index

         Envelopes : Envelope_Vectors.Vector;
      end record;

      overriding
      procedure Finalize (This : in out Arena);
      -- Deallocates all allocated memory from the heap

   end Arena_Pools;

   package body Arena_Pools is

      function Make return Slots_Envelope_Ptr is
         Envelope : Slots_Envelope_Ptr := new Slots_Envelope;
      begin
         Envelope.Free_Indices.Reserve_Capacity (MAX);
         for I in Slot_Index'Range loop
            Envelope.Free_Indices.Append (Free_Index (I));
         end loop;

         return Envelope;
      end Make;

      function Make return Arena is
         Envelope : Slots_Envelope_Ptr := Make;
      begin
         return This : Arena do
            This.Envelopes.Append (Envelope);
         end return;
      end Make;

      function Determine_Index (Pool    : Arena;
                                Address : System.Address) return Positive is
         Searched_For : Natural := 0;
         First_Address : System.Address;
         Last_Address  : System.Address;
      begin
         for I in Pool.Envelopes.First_Index..Pool.Envelopes.Last_Index loop
            First_Address := Pool.Envelopes (I).Items (1)'Address;
            Last_Address  := Pool.Envelopes (I).Items (MAX)'Address;
            if
              To_Integer (First_Address) <= To_Integer (Address) and
              To_Integer (Address)       <= To_Integer (Last_Address)
            then
               Searched_For := I;
               exit;
            end if;
         end loop;

         if Searched_For = 0 then
            raise Storage_Error;
         end if;

         return Searched_For;
      end Determine_Index;

      procedure Allocate
        (Pool      : in out Arena;
         Address   : out System.Address;
         Size      : Storage_Count;
         Alignment : Storage_Count)
      is
         Id : Slot_Index;
      begin
         if Pool.Envelopes (Pool.Index).Free_Indices.Length > 0 then
            Id := Slot_Index (Pool.Envelopes (Pool.Index).Free_Indices.Last_Element);
            Pool.Envelopes (Pool.Index).Free_Indices.Delete_Last;
         else
            declare
               Has_Found : Boolean := False;
            begin
               for I in Pool.Envelopes.First_Index .. Pool.Envelopes.Last_Index loop
                  if Pool.Envelopes (I).Free_Indices.Length > 0 then
                     Pool.Index := I;
                     Id := Slot_Index (Pool.Envelopes (Pool.Index).Free_Indices.Last_Element);
                     Pool.Envelopes (Pool.Index).Free_Indices.Delete_Last;
                     Has_Found := True;
                     exit;
                  end if;
               end loop;

               if not Has_Found then
                  declare
                     E : Slots_Envelope_Ptr := Make;
                  begin
                     Pool.Envelopes.Append (E);
                     Pool.Index := Pool.Envelopes.Last_Index;
                     Id := Slot_Index (Pool.Envelopes (Pool.Index).Free_Indices.Last_Element);
                     Pool.Envelopes (Pool.Index).Free_Indices.Delete_Last;
                  end;
               end if;
            end;
         end if;

         Put ("Will allocate (array, slot) := (");
         Put (Pool.Index);
         Put (",");
         Put (Id);
         Put_Line (")");

         Address := Pool.Envelopes (Pool.Index).Items (Id).Elements'Address;
      end Allocate;

      procedure Deallocate (Pool      : in out Arena;
                            Address   : System.Address;
                            Size      : Storage_Count;
                            Alignment : Storage_Count)
      is
         I : constant Positive := Determine_Index (Pool, Address);

         First_Address : System.Address;
         Last_Address  : System.Address;

         Slot_Id : Slot_Index;

         D : Integer_Address;
      begin
         First_Address := Pool.Envelopes (I).Items (1)'Address;
         Last_Address  := Pool.Envelopes (I).Items (MAX)'Address;

         D := (To_Integer (Last_Address) - To_Integer (First_Address) + Slot_Size) / MAX;

         Slot_Id := Slot_Index ((To_Integer (Address) + Slot_Size - To_Integer (First_Address))/ D);

         Pool.Envelopes (I).Free_Indices.Append (Free_Index (Slot_Id));

         Put ("Deallocate (array, slot) := (");
         Put (I);
         Put (",");
         Put (Slot_Id);
         Put_Line (")");
      end Deallocate;

      function Storage_Size (Pool : Arena) return Storage_Count is
         Result : Storage_Count := 0;
      begin
         for Envelope of Pool.Envelopes loop
            Result := Slot_Size*MAX + Storage_Count (Envelope.Free_Indices.Capacity * 4);
         end loop;

         return Result;
      end Storage_Size;

      procedure Free is new Ada.Unchecked_Deallocation (Object => Slots_Envelope,
                                                        Name   => Slots_Envelope_Ptr);

      procedure Finalize (This : in out Arena) is
      begin
         for Envelope of This.Envelopes loop
            Free (Envelope);
         end loop;
         This.Envelopes.Clear;
         Put_Line ("Deallocated all heap-allocated memory");
      end Finalize;

   end Arena_Pools;

   Pool : Arena_Pools.Arena := Arena_Pools.Make;

   type Integer_Ptr is access Integer with
     Storage_Pool => Pool;

   procedure Free is new Ada.Unchecked_Deallocation (Object => Integer,
                                                     Name   => Integer_Ptr);

   X : Integer_Ptr := new Integer'(1);
   Y : Integer_Ptr := new Integer'(2);
   Z : Integer_Ptr := new Integer'(3);

begin
   Free (X);
   Free (Y);
   Free (Z);
   Put_Line ("Has allocated" & Pool.Storage_Size'Image & " bytes.");
end Main;

It has the following output:
Will allocate (array, slot) := (1,200000)
Will allocate (array, slot) := (1,199999)
Will allocate (array, slot) := (1,199998)
Deallocate (array, slot) := (1,200000)
Deallocate (array, slot) := (1,199999)
Deallocate (array, slot) := (1,199998)
Has allocated 4800000 bytes.
Deallocated all heap-allocated memory


The implementation is inspired from Rosetta stone Arena pools:
http://rosettacode.org/wiki/Arena_storage_pool#Ada

^ permalink raw reply	[relevance 4%]

* Re: Should exceeding the range of Integer wrap around a la C?
  2018-05-21 15:23  5% Should exceeding the range of Integer wrap around a la C? nrs5134
@ 2018-05-21 15:45  0% ` Anh Vo
  0 siblings, 0 replies; 200+ results
From: Anh Vo @ 2018-05-21 15:45 UTC (permalink / raw)


On Monday, May 21, 2018 at 8:23:21 AM UTC-7, nrs...@gmail.com wrote:
> Hi all,
> 
> I'm brand-new to Ada coming from a Fortran & Python background - just starting to write some trivial tutorial programs. I'm trying to understand the output of following program (copied from the "Lovelace" Ada95 tutorial):
> 
> -- compute.adb
> -- Demonstrate a trivial procedure, with another nested inside.
> with Ada.Text_IO, Ada.Integer_Text_IO;
> use Ada.Text_IO, Ada.Integer_Text_IO;
> 
> procedure Compute is
>    
>    procedure Double(Item : in out Integer) is
>    begin -- procedure Double
>       Item := Item * 2;
>    end Double;
>    
>    X : Integer := 1; -- Local variable X of type Integer
>    
> begin -- procedure Compute
>    loop 
>       Put(X);
>       New_Line;
>       Double(X);
>    end loop;
> end Compute;
> 
> I expect this program to print powers of 2 until `X` exceeds the range of Integer. Instead, it seems to "wrap around" with the following (abbreviated) output:
>           1
>           2
>           4
>       [...]          
>   268435456
>   536870912
>  1073741824
> -2147483648
>           0
>           0
>       [...]
>           0
> 
> I am compiling with GNAT 4.9.2 on a Debian Linux system using `gnat make compute` with no further compiler flags. Are my expectations wrong, or is this incorrect behavior?

A Constraint_Error must be raised. If not, it is a compiler bug.

Anh Vo

^ permalink raw reply	[relevance 0%]

* Should exceeding the range of Integer wrap around a la C?
@ 2018-05-21 15:23  5% nrs5134
  2018-05-21 15:45  0% ` Anh Vo
  0 siblings, 1 reply; 200+ results
From: nrs5134 @ 2018-05-21 15:23 UTC (permalink / raw)


Hi all,

I'm brand-new to Ada coming from a Fortran & Python background - just starting to write some trivial tutorial programs. I'm trying to understand the output of following program (copied from the "Lovelace" Ada95 tutorial):

-- compute.adb
-- Demonstrate a trivial procedure, with another nested inside.
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;

procedure Compute is
   
   procedure Double(Item : in out Integer) is
   begin -- procedure Double
      Item := Item * 2;
   end Double;
   
   X : Integer := 1; -- Local variable X of type Integer
   
begin -- procedure Compute
   loop 
      Put(X);
      New_Line;
      Double(X);
   end loop;
end Compute;

I expect this program to print powers of 2 until `X` exceeds the range of Integer. Instead, it seems to "wrap around" with the following (abbreviated) output:
          1
          2
          4
      [...]          
  268435456
  536870912
 1073741824
-2147483648
          0
          0
      [...]
          0

I am compiling with GNAT 4.9.2 on a Debian Linux system using `gnat make compute` with no further compiler flags. Are my expectations wrong, or is this incorrect behavior?

Cheers,
NS

^ permalink raw reply	[relevance 5%]

* Re: Standard."-" provided to "with function "-" (VAL1 : in VALUE_TYPE) return VALUE_TYPE is <>;" refused:
  @ 2018-04-06 20:09  4% ` Mehdi Saada
  0 siblings, 0 replies; 200+ results
From: Mehdi Saada @ 2018-04-06 20:09 UTC (permalink / raw)


Here's a minimal, compilable ... and so on ;-)
Well, not compilable because of you know what.
All with-ed things are packages, spreadsheets.formula_cells being a generic child of non-generic spreadsheets.

generic
   type VALUE_TYPE is private;
   with function "-" (VAL1, VAL2 : in VALUE_TYPE) return VALUE_TYPE is <>;
   with function "-" (VAL1 : in VALUE_TYPE) return VALUE_TYPE is <>;
   with function "**" (VAL1 : in Value_Type; VAL2 : in VALUE_TYPE) return VALUE_TYPE is <>;
   with function Factoriel (Val : in Value_Type) return Value_Type is <>;
   with function IMAGE (VAL: in value_type) return STRING;
package NUMERIC_SIGNATURE is end Numeric_Signature;


private with Spreadsheets;
package VIEWS.SPREADSHEET_bis with Elaborate_Body
is
   type SHEET_TYPE is abstract tagged limited private;
private
   use SPREADSHEETs;
   type SHEET_TYPE is abstract new Spreadsheet_Type with null record;

end VIEWS.SPREADSHEET_bis;

private with Spreadsheets;
package VIEWS.SPREADSHEET is
   TYPE SHEET_TYPE is limited private;
private
   use SPREADSHEETs;
   type SHEET_TYPE is new Spreadsheet_Type with null record;
end VIEWS.SPREADSHEET;

with NUMERIC_SIGNATURE, Ada.Text_IO, Ada.Float_Text_IO, ADA.Integer_Text_IO, Spreadsheets.String_Cells, Spreadsheets.Formula_Cells;
use Ada.Text_IO, SPREADSHEETs.String_Cells, Ada.Float_Text_IO, Ada.Integer_Text_IO;
package body VIEWS.SPREADSHEET is
   function Factoriel (Operand : in Float) return FLOAT is separate;
   function "**" (Operand, Exponent : in Float) return Float is separate;
   package P_Num is new NUMERIC_SIGNATURE                   -- L6
(VALUE_TYPE => Float,IMAGE => FLOAT'IMAGE, "-" => Standard."-");
   package Formula_Cells_Package is new Formula_Cells (P_NUM); -- L7
   use Formula_Cells_package;               -- L8
end VIEWS.SPREADSHEET;           -- L9

Same message with this simplified version:
6:04: instantiation abandoned
7:44: named association not allowed for overloaded formal
8:56: "P_NUM" is not visible
8:56: non-visible declaration at spreadsheets-formula_cells.ads:4
8:56: instantiation abandoned
9:08: "Formula_Cells_package" is undefined

^ permalink raw reply	[relevance 4%]

* Re: How to make tasks to run in parallel
  @ 2017-10-17  6:17  4% ` Per Sandberg
  0 siblings, 0 replies; 200+ results
From: Per Sandberg @ 2017-10-17  6:17 UTC (permalink / raw)


It won't run in parallel since all the computations are done within the 
roundevouz where both tasks are are running "in the same thread".
And also why a private Real type when there is a general Float.
Have a look on the updated code.
/P
----------------------------
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Float_Text_IO;
with Ada.Numerics.Elementary_Functions;

procedure Main is

    use Ada.Text_IO;
    use Ada.Integer_Text_IO;
    use Ada.Float_Text_IO;
    use Ada.Numerics.Elementary_Functions;

    N : constant Integer := 10_000_000;

    -- 
---------------------------------------------------------------------------
    task type Test1_T (A : access Float);

    task body Test1_T is
       X : Float := A.all;
    begin
       -- stupid time consuming loop:
       for I in 1 .. N loop
          X := X + Float (I) / Float (N);
          X := 0.5 * X + 1.0 + Sin (X) * Cos (X) + Sin (X) + Cos (X) +
            Sin (X) * Sin (X) + Cos (X) * Cos (X);
       end loop;
       New_Line; Put ("test1 x:"); Put (X, 4, 16, 0); New_Line (1);
    end Test1_T;
    -- 
---------------------------------------------------------------------------
    task type Test2_T is
       entry Run1 (A : in Float);
    end Test2_T;

    task body Test2_T is
       X : Float;
    begin
       accept Run1 (A : in Float) do
          X := A;
       end Run1;
       -- stupid time consuming loop:
       for I in 1 .. N loop
          X := X + Float (I) / Float (N);
          X := 0.5 * X + 1.0 + Sin (X) * Cos (X) + Sin (X) + Cos (X) +
            Sin (X) * Sin (X) + Cos (X) * Cos (X);
       end loop;
       New_Line; Put ("test2 x:"); Put (X, 4, 16, 0); New_Line (1);
    end Test2_T;

    X     : aliased Float;
    Y     : Float;
    Dx, Dy : constant := 0.5;

    Test1 : array (1 .. 4) of access Test1_T;
    Test2 : array (1 .. 4) of access Test2_T;
    -- 
---------------------------------------------------------------------------

begin

    -- This goes in parallel:
    X := 1.0;
    for E of Test1 loop
       X := X + Dx;
       Put_Line (" Test1: ");
       E := new Test1_T (A => X'Access);
    end loop;

    Y := 1.0;
    for E of Test2 loop
       Y := Y + Dy;
       Put_Line (" Test2: ");
       E := new Test2_T;
       E.Run1 (Y);
    end loop;

end Main;
---------------------------------------------------------------------





Den 2017-10-17 kl. 06:58, skrev reinert:
> Hi,
> 
> The test program below includes two tasks. The first task gets an "argument" (input data) via a discriminant. The other task gets data via entry/accept. The first task runs easily in parallel. The other not.
> 
> I would prefer to enter data via entry/accept. But is it possible without giving up parallel processing? I feel it is something I should understand better here :-)
> 
> reinert
> 
> 
> with Text_IO;       use Text_IO;
> with Ada.Numerics.Generic_Elementary_Functions;
> with Ada.Text_IO;
> procedure ttest1 is
>    type Real is new Float;
>    package Flt_Io is new Text_IO.Float_Io   (Real);
>    package Int_Io is new Text_IO.Integer_Io (Integer);
>    package E_F is new Ada.Numerics.Generic_Elementary_Functions (Real);
>    use E_F,Flt_Io,Int_Io;
> 
>    N : constant Integer := 10_000_000;
> 
> -- ---------------------------------------------------------------------------
>    task type test1_t(a : access real);
> 
>    task body test1_t is
>        x : real := a.all;
>    begin
> -- stupid time consuming loop:
>        for I in 1 .. N loop
>            x := x + Real(I)/Real(N);
>            x := 0.5*x + 1.0 + sin(x)*cos(x) + sin(x) + cos(x) +
>                               sin(x)*sin(x) + cos(x)*cos(x);
>        end loop;
>        new_line;Put("test1 x:");Put (x,4,16,0); New_Line (1);
>    end test1_t;
> -- ---------------------------------------------------------------------------
>    task type test2_t is
>       entry run1(a : in real);
>    end test2_t;
> 
>    task body test2_t is
>      x : real;
>    begin
>        accept run1(a : in real) do
>          x := a;
> -- stupid time consuming loop:
>          for I in 1 .. N loop
>              x := x + Real(I)/Real(N);
>              x := 0.5*x + 1.0 + sin(x)*cos(x) + sin(x) + cos(x) +
>                               sin(x)*sin(x) + cos(x)*cos(x);
>          end loop;
>          new_line;Put("test2 x:");Put (x,4,16,0); New_Line (1);
>          return;
>        end run1;
>    end test2_t;
> 
>    x : aliased real;
>    y : real;
>    dx,dy : constant := 0.5;
> 
>    test1 : array(1..4) of access test1_t;
>    test2 : array(1..4) of access test2_t;
> -- ---------------------------------------------------------------------------
> 
> begin
> 
> -- This goes in parallel:
>       x := 1.0;
>       for e of test1 loop
>           x := x + dx;
>           Put_Line(" Test1: ");
>           e := new test1_t(a => x'access);
>       end loop;
> 
> -- This goes *not* in parallel (why?):
>       y := 1.0;
>       for e of test2 loop
>           y := y + dy;
>           Put_Line(" Test2: ");
>           e := new test2_t;
>           e.run1(y);
>       end loop;
> 
> end ttest1;
> 


^ permalink raw reply	[relevance 4%]

* using a type record's components:
@ 2017-09-14 19:41  4% Mace Ayres
  0 siblings, 0 replies; 200+ results
From: Mace Ayres @ 2017-09-14 19:41 UTC (permalink / raw)


1) In a package specification I have defined a record type ( i had errors in putting it in the body)
    Is that wrong, should the record info be both in package specification and body, like everything else?
2) record type is:

package structures is  -- specification
function sayhi(strin : in String) return String; 
function report_self(layer,numb: in Integer) return String;
procedure set_up;

type a_cell is
      record
         numb:  integer range 1..100;
         row:   integer range 1..10;
         col:   integer range 1..10;
         layer: integer range 1..10;
         valu:  integer range 0..9;
         fixd:  BOOLEAN           ;
      end record;
end structures;

-------
in package body -- separate file
..
..
with Ada.Integer_Text_IO;
use  Ada.Integer_Text_IO;

type cell   is new a_cell; 
type layer  is array(1..100) of cell;
layer_0   : layer;
      
begin
   ...
   for i of layer_1 loop
         ....
         New_Line;
         layer_0(i).numb := i;
         ..
         Put (layer_0.cell.numb, Width =>2);
         Put( " Cell x has numb value "); 
         --Put (layer_0(i).numb) ;
         New_Line;
   end loop;

I can't access the record type 'cell's component '.numb" which i tried to assign the value of the loop index i.

I do have a record cell function to report on itself, a stub. Do I a function like this to get to the record's numb value?

-- this is just a stub for now
FUNCTION report_self(layer,numb: in Integer) return STRING is
    --cell_status: STRING (1..100) ;
    begin
      --cell_status :=  "";
      New_Line(2);
      return ("Layer , row y column z has value of 0 and is not fixed");

end report_self;


^ permalink raw reply	[relevance 4%]

* Getting the index for an element in mutually referencing containers
@ 2017-03-09 13:45  4% Mart van de Wege
  0 siblings, 0 replies; 200+ results
From: Mart van de Wege @ 2017-03-09 13:45 UTC (permalink / raw)



I am missing another thing: I managed to boil down the problem to the
PoC code below. I want to have two objects, each with a container as a
record attribute, referring to each other, and then merely get the index
value of one of the two containers. Yet if I do, I get a Storage_Error
exception.

Code:

with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Doubly_Linked_Lists;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Test_Container is
   type Abstract_Person is abstract tagged null record;
   package Offspring is new Ada.Containers.Indefinite_Vectors
     (Index_Type => Positive,
      Element_Type => Abstract_Person'Class);
   package Group is new Ada.Containers.Indefinite_Doubly_Linked_Lists
     (Element_Type => Abstract_Person'Class);
   type Person is new Abstract_Person with record
      Children : Offspring.Vector := Offspring.To_Vector(4);
      Parents : Group.List;
   end record;
   Father : Person;
   Child : Person;
begin
   Child.Parents.Prepend(Father);
   Father.Children.Append(Child);
   Put(Integer(Father.Children.Find_Index(Child)));
end Test_Container;

This compiles OK, but on runtime throws an exception:

raised STORAGE_ERROR : stack overflow or erroneous memory access

Now, cyclic dependencies are tricky, so I am sure I am doing something
wrong, but I can't for the life of me see what.

Mart

-- 
"We will need a longer wall when the revolution comes."
    --- AJS, quoting an uncertain source.

^ permalink raw reply	[relevance 4%]

* Re: Question: Ordered Loading of an Array.
  2017-02-04 12:41  0% ` AdaMagica
@ 2017-02-04 15:34  0%   ` Austin Obyrne
  0 siblings, 0 replies; 200+ results
From: Austin Obyrne @ 2017-02-04 15:34 UTC (permalink / raw)


On Saturday, February 4, 2017 at 12:41:05 PM UTC, AdaMagica wrote:
> Am Samstag, 4. Februar 2017 10:55:29 UTC+1 schrieb Austin Obyrne:
> 
> Not mentioning typos.
> 
> > This_Num : Integer;  -- Why isn't this of subtype Index_1?
> 
> > 
> > SUBTYPE Index_1 IS Integer RANGE 32 .. 126;
> > TYPE This_NumArray IS ARRAY(Index)_1 OF Integer;
> > Cell_Num : This_NumArray:= (others =>0);
> > 
> > Input Program:
> > 
> > For I in  1 .. 95 Loop ;
> > Ada.Text_IO. Put(Item => "Please enter any integer in the range 32 to 126");
> No range check here! Why?
> 
> > Ada.Integer_Text_IO.Get (Item => This_Num);
> > Cell_Num := This_Num;  -- What's this line?
> 
> > Cell_Num(This_Num) := Cell_Num(This_Num) +1;
Hi,

<This_Num : Integer;  -- Why isn't this of subtype Index_1? 

This is extraneous - careless of me

As It happens I think I have resolved my problem at home - many thanks - Austin.

^ permalink raw reply	[relevance 0%]

* Re: Question: Ordered Loading of an Array.
  2017-02-04  9:55  2% Question: Ordered Loading of an Array Austin Obyrne
@ 2017-02-04 12:41  0% ` AdaMagica
  2017-02-04 15:34  0%   ` Austin Obyrne
  0 siblings, 1 reply; 200+ results
From: AdaMagica @ 2017-02-04 12:41 UTC (permalink / raw)


Am Samstag, 4. Februar 2017 10:55:29 UTC+1 schrieb Austin Obyrne:

Not mentioning typos.

> This_Num : Integer;  -- Why isn't this of subtype Index_1?

> 
> SUBTYPE Index_1 IS Integer RANGE 32 .. 126;
> TYPE This_NumArray IS ARRAY(Index)_1 OF Integer;
> Cell_Num : This_NumArray:= (others =>0);
> 
> Input Program:
> 
> For I in  1 .. 95 Loop ;
> Ada.Text_IO. Put(Item => "Please enter any integer in the range 32 to 126");
No range check here! Why?

> Ada.Integer_Text_IO.Get (Item => This_Num);
> Cell_Num := This_Num;  -- What's this line?

> Cell_Num(This_Num) := Cell_Num(This_Num) +1;


^ permalink raw reply	[relevance 0%]

* Question: Ordered Loading of an Array.
@ 2017-02-04  9:55  2% Austin Obyrne
  2017-02-04 12:41  0% ` AdaMagica
  0 siblings, 1 reply; 200+ results
From: Austin Obyrne @ 2017-02-04  9:55 UTC (permalink / raw)


My interest is in cryptography programming and I have a particular one-off problem that readers may be able to shed some light on.  I have invented a solution that works very well but it needs to be ratified by more knowledgeable people before I would go public in a cipher program with it.

Basically it involves loading on-going fallout elements as they occur in a running program procedure (say) at run time into specifically selected cells of an array in a pre-ordained order, this could be the natural order of each named elemnet or anything other order that is required.

This discussion model here is meant to be simplistic in the extreme and it simulates loading casually inputted code-points of ASCII(say)into a program array in a stipulated correct order and read back later - this is just a short demo being used as a discussion model.

What I am doing is not normal because data is most often assigned to an array just as it occurs in consecutive order.

Please take this simple model with a pinch of salt.

Declarations:

This_Num : Integer;

SUBTYPE Index_1 IS Integer RANGE 32 .. 126;
TYPE This_NumArray IS ARRAY(Index)_1 OF Integer;
Cell_Num : This_NumArray:= (others =>0);

Input Program:

For I in  1 .. 95 Loop ;
Ada.Text_IO. Put(Item => "Please enter any integer in the range 32 to 126");
Ada.Integer_Text_IO.Get (Item => This_Num);
Cell_Num := This_Num;
Cell_Num(This_Num) := Cell_Num(This_Num) +1;

This short loop puts each integer(This_Num) into its specifically correct cell and not just the next consecutive empty cell i.e. it places each integer into its named cell in strict order and not just any order.  It will increment a cell with an extra (error) element in the case of a repeat.  The errant cell can then be trimmed correctly against the empty cell it must inevitably leave.

This is a personally devised ploy that I would like to use with impunity in the future but I hesitate to do so because I cannot find anything in the language RM that supports it.  It is a very useful tool in cryptography but I am not prepared to use without some proof that it is reliable.  I have other options that I will use instead if needs be but it would be very convenient as a general tool if I could use this one.

My gut feeling is NO.

Although this ploy has never let me down I fear that it could and since I am not a language expert I will wait for some advice from language orientated people who know more about it before I use it indiscriminately.

I would be very grateful to anybody who can say with conviction that it is safe to use or not.

It strikes me that the custodians of the Ada language (back at the ranch) might consider adding an array loading package along such lines if it does not already exist.

Scríofa ag adacrypt


^ permalink raw reply	[relevance 2%]

* Re: I am not understanding user defined exceptions
  2017-02-03 20:27  5% I am not understanding user defined exceptions patrick
@ 2017-02-04  1:26  5% ` Dennis Lee Bieber
  0 siblings, 0 replies; 200+ results
From: Dennis Lee Bieber @ 2017-02-04  1:26 UTC (permalink / raw)


On Fri, 3 Feb 2017 12:27:09 -0800 (PST), patrick@spellingbeewinnars.org
declaimed the following:

>
>If we type something like :    
>         if x = 1
>         then
>           raise Foo_Error;
>         end if ;
> 
>will x not be tested for exceptions conditions automatically from that point onward? If so, why would it not raise an exception if the second text_io.get came back with 1 ?
>

	No... because that is just a sequence of statements that only take
effect /at that location/. Ada doesn't magically go back and apply that
code whenever you do something with the variable X.

	If you always need to have input of a 1 raise the exception, you need
to encapsulate the input with the test. See below:

-=-=-=-=-=-
with Ada.Integer_Text_Io;
with Ada.Text_IO;

procedure Test_Exceptions is
   
   Foo_Error : exception;
   
   X : Integer;
   
   procedure Get_Int (An_Int : out Integer) is
   begin
      Ada.Text_IO.Put ("Enter an integer => ");
      
      Ada.Integer_Text_IO.Get (An_Int);
      
      if An_Int = 1 then
	 raise Foo_Error;
      end if;
   end Get_Int;
   
begin
   Get_Int (X);   -- first input point
   Get_Int (X);    -- second input point
   
   Ada.Text_Io.Put_Line ("Ended without exceptions...");
      
exception
   when Foo_Error =>
      Ada.Text_Io.Put_Line ("Error handled...");
      
end Test_Exceptions;

-=-=-=-=-=-

C:\Users\Wulfraed\Ada>test_exceptions
Enter an integer => 1
Error handled...

C:\Users\Wulfraed\Ada>test_exceptions
Enter an integer => 2
Enter an integer => 1
Error handled...

C:\Users\Wulfraed\Ada>test_exceptions
Enter an integer => 3
Enter an integer => 2
Ended without exceptions...
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/


^ permalink raw reply	[relevance 5%]

* I am not understanding user defined exceptions
@ 2017-02-03 20:27  5% patrick
  2017-02-04  1:26  5% ` Dennis Lee Bieber
  0 siblings, 1 reply; 200+ results
From: patrick @ 2017-02-03 20:27 UTC (permalink / raw)


Hi Everyone

I am not understanding user defined exceptions. This little program will ask the user for integer entry twice. If I type 1 at the first entry, things work as expected and the exception is handled.

However if I type, 2 and then 1, an exception is not raised at the second text_io.get.

If we type something like :    
         if x = 1
         then
           raise Foo_Error;
         end if ;
 
will x not be tested for exceptions conditions automatically from that point onward? If so, why would it not raise an exception if the second text_io.get came back with 1 ?

Sorry for what will very likely be a stupid question-Patrick






          with ada.integer_text_io ;
          with ada.text_io ;
       --
       --
       --
       --
       --
       --
        procedure test_exceptions is

        package text_io renames ada.text_io ;
        package int_text_io renames ada.integer_text_io ;

        Foo_Error : exception ;
        x : integer ;
        begin
           
         int_text_io.get(x) ;

         if x = 1
         then
           raise Foo_Error;
         end if ;
 

         int_text_io.get(x) ;

     -- why does execution reach this point if x is 1 after user input
         if x = 1
         then
            text_io.put_line("x is 1, why wasn't an exception triggered?") ;
         end if ;
 

        text_io.put_line("ended without exceptions") ;


        exception
           when Foo_Error =>
              text_io.put("error handled") ;
        end test_exceptions;


^ permalink raw reply	[relevance 5%]

* Re: Passing a 2d array into a package and returning the same processed 2d back to main
  @ 2016-10-05 17:19  3%           ` James Brewer
  0 siblings, 0 replies; 200+ results
From: James Brewer @ 2016-10-05 17:19 UTC (permalink / raw)



Well, I thought it worked by I'm just getting 1's for the output.

I'll post the new code if you all are still interested in helping me out.

                 -- Interface of WarshallsPkg

PACKAGE WarshallsPkg IS

   TYPE MY_ARRAY IS ARRAY(INTEGER RANGE <>, INTEGER RANGE <>) OF Boolean;

   PROCEDURE WarshallExecute(Arr : IN OUT MY_ARRAY);

end WarshallsPkg;

                 -- Implementation of WarshallsPkg

PACKAGE BODY WarshallsPkg IS
   PROCEDURE WarshallExecute(Arr : IN OUT My_Array) IS
   BEGIN
      FOR I IN Arr'RANGE LOOP
         FOR J IN Arr'RANGE LOOP
            IF Arr(J,I) THEN --true nodes connected
               FOR K IN Arr'RANGE LOOP
                  Arr(J,K) := Arr(J,K) OR Arr(I,K);
               END LOOP;
            END IF;
         END LOOP;
      END LOOP;
   END WarshallExecute;
END WarshallsPkg;

-- Lab 1 C version read and write to file use package
-- Programmed by James Brewer
-- Version 12

--put this in every program for now
--WITH Ada.Command_Line;
WITH Text_IO; USE Text_IO; -- This gets the IO facility.
WITH Ada.Integer_Text_IO; USE Ada.Integer_Text_IO; -- This gets the integer IO facility.
WITH WarshallsPkg; USE WarshallsPkg; --package setup


-- * main procedure *
PROCEDURE WarshallsMain IS

   Input : File_Type; -- input file declaration
   Output : File_Type; -- output file declaration
   N : Integer := 9; -- max size of array -- why does this overflow if not set?
   YOrN : String(1..1); -- y or n for node connections
   OutputConvertion : Integer; -- used for conversion from true/false to 1/0

   TestString : String(1..1);

-- highlight section in code that creates the array
--   Array2d: ARRAY (1..N, 1..N) OF Boolean; --****** highlight this section ********
   Array2d: WarshallsPkg.MY_ARRAY(1..N,   1..N);



-- * main procedure starts begins*
BEGIN
-- try to use io redirection to pull data from file
-- open input.txt file
   Open (File => Input,
         Mode => In_File,
         Name => "input.txt");


-- output to file creation section
   Create (File => Output,
      Mode => Out_File,
      Name => "output.txt");

-- input node connection data collection
   -- ask for size of array
   Put("How many nodes need to be processed? ");
   TestString := Get_Line (Input); -- get number of nodes
   N := Integer'Value(TestString); -- convert number of nodes to Integer
   put(N); -- display n on screen
--   Get(N); -- ** not used
   New_Line(2);

   FOR X IN 1..N LOOP
      FOR Y IN 1..N LOOP
         Put("Is node");
         Put(X);
         Put(" connected to node ");
         Put(Y);
         Put(" y/n ");
         YOrN := Get_Line(Input);
 --        Get(YOrN); -- ** not used
         put(YOrN); new_line(1); -- display choice on screen
         if yOrN = "y" then
            Array2d(X,Y) := True;
         ELSE Array2d(X,Y) := False;
         END IF;
      END LOOP;
   END LOOP;


-- Warshallpkg implementation

   WarshallExecute(Array2d);
--      FOR I IN 1..N LOOP
--      FOR J IN 1..N LOOP
--         IF Array2d(J,I) = True THEN --true nodes connected
--            FOR K IN 1..N LOOP
--               Array2d(J,K) := Array2d(J,K) OR Array2d(I,K);
--            END LOOP;
--         END IF;
--      END LOOP;
--   END LOOP;


-- print each transaction as it is processed

-- *********** output to file ************

-- column label output
   New_Line(Output, 2);
   Put(Output, "           ");
   FOR I IN 1..N LOOP
      Put(Output, I);
   END LOOP;
   New_Line(Output, 1);

-- data matrix output
   FOR I IN 1..N LOOP
      Put(Output, I);
      FOR J IN 1..N LOOP
         IF Array2d(I,J) = True THEN
            OutputConvertion := 1;
         ELSE
            OutputConvertion := 0;
         END IF;
         Put(Output, OutputConvertion);
      END LOOP;
      New_Line(Output, 1);
   END LOOP;

--close files
   Close (Input);
   Close (Output);
exception
   when End_Error =>
      if Is_Open(Input) then
         Close (Input);
      end if;
      if Is_Open(Output) then
         Close (Output);
      end if;

END WarshallsMain;
-- * main procedure ends *


^ permalink raw reply	[relevance 3%]

* Re: Passing a 2d array into a package and returning the same processed 2d back to main
  @ 2016-10-03 18:36  3% ` James Brewer
    0 siblings, 1 reply; 200+ results
From: James Brewer @ 2016-10-03 18:36 UTC (permalink / raw)


On Friday, September 30, 2016 at 5:28:01 PM UTC-5, dia...@gmail.com wrote:
> Hello again, new Ada programmer with a hopefully easy question. 
> I am trying to take a 2d array pass it to a package have the package change the data in the 2d array and send the same 2d array (with modified data) back to the main program. I am currently away from my computer or I would show you my broken code, though I doubt it would be useful. 
> 
> Thanks

I may not have given enough information for help with this problem. So here is my attempt to clarify what I am trying to do by posting my nonfunctioning code.

                 -- Interface of WarshallsPkg

PACKAGE WarshallsPkg IS
   
   TYPE MY_ARRAY IS ARRAY(INTEGER RANGE <>, INTEGER RANGE <>) OF Boolean;  
   PROCEDURE WarshallExecute(InArray : IN MY_ARRAY; OutArray : OUT MY_ARRAY);
   
end WarshallsPkg;

                 -- Implementation of WarshallsPkg

PACKAGE BODY WarshallsPkg IS
   
   PROCEDURE WarshallExecute(InArray : IN MY_ARRAY; OutArray : OUT MY_ARRAY) IS

--   TestArray: ARRAY(InArray'FIRST..InArray'LAST) OF Integer;

   BEGIN
   FOR I IN InArray'FIRST..InArray'LAST LOOP
      FOR J IN InArray'FIRST..InArray'LAST LOOP
         IF InArray(J,I) = True THEN --true nodes connected
            FOR K IN InArray'FIRST..InArray'LAST LOOP
               OutArray(J,K) := InArray(J,K) OR InArray(I,K);
            END LOOP;
         END IF;
      END LOOP;
   END LOOP;

   END WarshallExecute;
   
END WarshallsPkg;

                      --The program i'm trying to implement it in

WITH Text_IO; USE Text_IO; -- This gets the IO facility.
WITH Ada.Integer_Text_IO; USE Ada.Integer_Text_IO; -- This gets the integer IO facility.
WITH WarshallsPkg; USE WarshallsPkg; --package setup


-- * main procedure *
PROCEDURE WarshallsMain IS

   Output : File_Type; -- output file declaration
   N : Integer := 9; -- max size of array -- why does this overflow if not set?
   yOrN : character; -- user input yes or no
   OutputConvertion : Integer; -- used for conversion from true/false to 1/0
   Array2d: ARRAY (1..N, 1..N) OF Boolean;
      
--  PROCEDURE testExecute(InArray : IN MY_ARRAY; OutArray : OUT MY_ARRAY); -- renames warshall proceedure


-- * main procedure starts begins*
BEGIN
-- try to use io redirection to pull data from file

-- output to file creation section
   Create (File => Output,
      Mode => Out_File,
      Name => "output.txt");

-- input node connection data collection
   -- ask for size of array
   Put("How many nodes need to be processed? ");
   Get(N);
   New_Line(2);

   FOR X IN 1..N LOOP
      FOR Y IN 1..N LOOP
         Put("Is node");
         Put(X);
         Put(" connected to node ");
         Put(Y);
         Put(" y/n ");
         Get(YOrN);

         if yOrN = 'y' then
            Array2d(X,Y) := True;
         ELSE Array2d(X,Y) := False;
         END IF;
      END LOOP;
   END LOOP;


-- Warshall's alorithm

-- implement proceedure here for Array2d

   WarshallExecute(Array2d, Array2d);
 
-- to be removed   
--   FOR I IN 1..N LOOP
--      FOR J IN 1..N LOOP
--         IF Array2d(J,I) = True THEN --true nodes connected
--            FOR K IN 1..N LOOP
--               Array2d(J,K) := Array2d(J,K) OR Array2d(I,K);
--            END LOOP;
--         END IF;
--      END LOOP;
--   END LOOP;

-- end of code to be removed

-- *********** output to file ************

-- column label output
   New_Line(Output, 2);
   Put(Output, "           ");
   FOR I IN 1..N LOOP
      Put(Output, I);
   END LOOP;
   New_Line(Output, 1);

-- data matrix output
   FOR I IN 1..N LOOP
      Put(Output, I);
      FOR J IN 1..N LOOP
         IF Array2d(I,J) = True THEN
            OutputConvertion := 1;
         ELSE
            OutputConvertion := 0;
         END IF;
         Put(Output, OutputConvertion);
      END LOOP;
      New_Line(Output, 1);
   END LOOP;

END WarshallsMain;
-- * main procedure ends *

^ permalink raw reply	[relevance 3%]

* Re: New to Ada need help implementing Warshall's algorithm
  2016-09-26 17:38  4% ` James Brewer
@ 2016-09-26 18:29  0%   ` Stephen Leake
  0 siblings, 0 replies; 200+ results
From: Stephen Leake @ 2016-09-26 18:29 UTC (permalink / raw)


On Monday, September 26, 2016 at 12:38:16 PM UTC-5, James Brewer wrote:
> example:
> 
>          ColName1 ColName2 ColName3 ColNameN
> RowName1    0        0        0        0
> RowName2    1        1        1        1
> RowName3    0        1        0        0
> RowNameN    0        1        1        0
> 
> 
> WITH Text_IO; USE Text_IO;      -- This gets the IO facility.
> WITH Ada.Integer_Text_IO; USE Ada.Integer_Text_IO; -- This gets the integer IO facility.
> --****
> -- use zero elements in array to store size 0,0 and row/column names?

not necessary.

> -- read size

Read the first line, count the spaces (trim trailing spaces if needed).

use Ada.Strings.Fixed.Index to find the spaces.

> -- use size to read names of columns

split the first line at the spaces.

> -- use size to read first row of data?

Read the whole line, split at spaces.

> -- if value read = 0 => array2d(n,n) = false

can be:

array2d(n, n) := read = 0;

--  Stephe

^ permalink raw reply	[relevance 0%]

* Re: New to Ada need help implementing Warshall's algorithm
  @ 2016-09-26 17:38  4% ` James Brewer
  2016-09-26 18:29  0%   ` Stephen Leake
  0 siblings, 1 reply; 200+ results
From: James Brewer @ 2016-09-26 17:38 UTC (permalink / raw)


Thought I would clarify my previous post. So here it goes.

Ideally, the input data will look like this (the number of row and columns will vary and there will be more than one set (matrix) of data with different row and column names in the input file.

example:

         ColName1 ColName2 ColName3 ColNameN
RowName1    0        0        0        0
RowName2    1        1        1        1
RowName3    0        1        0        0
RowNameN    0        1        1        0


Here is the code I have so far without the read from file and output to file implementation.


WITH Text_IO; USE Text_IO;      -- This gets the IO facility.
WITH Ada.Integer_Text_IO; USE Ada.Integer_Text_IO; -- This gets the integer IO facility.
--****
-- use zero elements in array to store size 0,0 and row/column names?


-- read size
-- use size to read names of columns
-- store in array


-- use size to read first row of data?
-- as data is read convert from 0/1 to true false and store?

-- if value read = 0 => array2d(n,n) = false
-- if value read = 1 => array2d(n,n) = true


-- * main procedure *
PROCEDURE BooleanTest IS              -- Main, but no special name is needed.BEGIN

   N : Integer := 4; -- max size ** to be read
   OutputConvertion : Integer;
   Array2d: ARRAY (1..N, 1..N) OF boolean;

-- * main procedure starts begins*
BEGIN
   -- read array size and column names

   -- hard coded to be read from file
   
   Array2d(1, 1) := false;
   Array2d(1, 2) := false;
   Array2d(1, 3) := false;
   Array2d(1, 4) := false;

   Array2d(2, 1) := false;
   Array2d(2, 2) := true;
   Array2d(2, 3) := false;
   Array2d(2, 4) := true;

   Array2d(3, 1) := false;
   Array2d(3, 2) := true;
   Array2d(3, 3) := false;
   Array2d(3, 4) := true;

   Array2d(4, 1) := true;
   Array2d(4, 2) := false;
   Array2d(4, 3) := true;
   Array2d(4, 4) := false;

   FOR I IN 1..N LOOP
      FOR J IN 1..N LOOP
         IF Array2d(J,I) = true THEN --true nodes connected
            FOR K IN 1..N LOOP
               Array2d(J,K) := Array2d(J,K) OR Array2d(I,K);
            END LOOP;
         END IF;
      END LOOP;
   END LOOP;

-- *********** output to screen ************

   FOR I IN 1..N LOOP
      FOR J IN 1..N LOOP
         IF Array2d(I,J) = True THEN
            OutputConvertion := 1;
         ELSE 
            OutputConvertion := 0;
         END IF;
         Put( OutputConvertion);
         Put(" ");                
      END LOOP;
      New_Line(1);
   END LOOP;
   

END BooleanTest;
-- * main procedure ends *

Thanks again for all the help.


^ permalink raw reply	[relevance 4%]

* Re: Question on bounded / unbounded strings
  @ 2016-09-14 11:23  4% ` Arie van Wingerden
  0 siblings, 0 replies; 200+ results
From: Arie van Wingerden @ 2016-09-14 11:23 UTC (permalink / raw)


Hi,
thank you *very* much. You are very helpful!

I created the following program, which only uses standard strings. It works 
partly.

There is one thing I cannot get to work properly:
    in the FOR loop the statement:
         ATIO.Put(Path(Start .. Len));
    outputs the first part of Path properly; but in the following cases it 
won't.
What am I doing wrong?

(Don't mind the matching; this is NOT correct currently).

(Wrongly indented pieces will be gone in final version.)

The program code (FIP stand for Find In Path):
======================================


with Ada.Text_Io;
    with Ada.Integer_Text_Io;
with Ada.Environment_Variables;
with Ada.Strings.Fixed;
with Ada.Strings.Maps.Constants;

procedure Fip is

    package ATIO   renames Ada.Text_IO;
package AITIO renames Ada.Integer_Text_Io;
    package AEV    renames Ada.Environment_Variables;
    package ASF    renames Ada.Strings.Fixed;
    package ASMC renames Ada.Strings.Maps.Constants;

    Path   : string := ASF.Translate(AEV.Value("Path"), 
ASMC.Lower_Case_Map);
    Match : string := ASF.Translate(ATIO.Get_Line, ASMC.Lower_Case_Map);

    procedure Match_Path (Match : in string; Path : in string) is
        Start : positive := 1;
        Len   : natural  := 0;
    begin
        for I in Path'Range loop
            if Path(I) = ';' then
ATIO.Put_Line("----------------------------------------------------");
ATIO.Put(Path(Start .. Len)); AITIO.Put(Start); AITIO.Put(Len); ATIO.Put(" 
"); ATIO.Put_Line(Match);
-- This matching part is not OK yet
                if Len > 0 and then Path(Start .. Len) = Match then
                    ATIO.Put_Line(Path(Start .. Len));
                end if;
                Start := I + 1;
                Len   := 0;
            else
                Len := Len + 1;
            end if;
        end loop;
    end Match_Path;

begin
    Match_Path(Match, Path);
    ATIO.Flush;
end Fip; 


^ permalink raw reply	[relevance 4%]

* Re: Why does this input get "skipped"?
  2016-08-21  1:04  4%       ` John Smith
@ 2016-08-21  4:07  0%         ` Jeffrey R. Carter
  0 siblings, 0 replies; 200+ results
From: Jeffrey R. Carter @ 2016-08-21  4:07 UTC (permalink / raw)


On 08/20/2016 06:04 PM, John Smith wrote:
> 
> Just to be sure, Speed_IO.Get, you meant Ada.Integer_Text_IO.Get, yes?
> 
> I've made mistakes like this, but I want to be sure that I'm on the right page as well.

Because it's a good idea to use types that reflect the problem, maybe something like

type Speed_Value is range 30 .. 150; -- Speeds the system can maintain, in kph

package Speed_IO is new Ada.Text_IO.Integer_IO (Num => Speed_Value);

-- 
Jeff Carter
"People called Romanes, they go the house?"
Monty Python's Life of Brian
79


^ permalink raw reply	[relevance 0%]

* Re: Why does this input get "skipped"?
  2016-08-21  0:50  0%     ` Jeffrey R. Carter
@ 2016-08-21  1:04  4%       ` John Smith
  2016-08-21  4:07  0%         ` Jeffrey R. Carter
  0 siblings, 1 reply; 200+ results
From: John Smith @ 2016-08-21  1:04 UTC (permalink / raw)


On Saturday, August 20, 2016 at 8:50:52 PM UTC-4, Jeffrey R. Carter wrote:
> On 08/20/2016 05:01 PM, John Smith wrote:
> > 
> > Hi, I do have an Ada.Integer_Text_IO.Get above this call (some ways above it.)
> > 
> > How can I clear out that line terminator?  Another call to Get_Line, but not save the input?
> 
> The way to skip the next line terminator in an input file is with a call to
> Skip_Line.
> 
> However, when using Text_IO for input from standard input, it's best to always
> input an entire line at a time into a String, and then deal with the line in the
> String. The fact that Get leaves a line terminator in the buffer wreaks havoc on
> error handling.
> 
> Get_Speed : loop
>    Ada.Text_IO.Put (Item => "Enter desired speed: ");
> 
>    Speed_Line : declare
>       Line : constant String := Ada.Text_IO.Get_Line;
> 
>       Last : Natural;
>    begin -- Speed_Line
>       Speed_IO.Get (From => Line, Item => Speed, Last => Last);
> 
>       exit Get_Speed;
>    exception -- Speed_Line
>    when others =>
>       Ada.Text_IO.Put_Line (Item => "Enter a valid speed.");
>    end Speed_Line;
> end loop Get_Speed;
> 
> -- 
> Jeff Carter
> "People called Romanes, they go the house?"
> Monty Python's Life of Brian
> 79

Just to be sure, Speed_IO.Get, you meant Ada.Integer_Text_IO.Get, yes?

I've made mistakes like this, but I want to be sure that I'm on the right page as well.

^ permalink raw reply	[relevance 4%]

* Re: Why does this input get "skipped"?
  2016-08-21  0:01  4%   ` John Smith
  2016-08-21  0:36  0%     ` John Smith
@ 2016-08-21  0:50  0%     ` Jeffrey R. Carter
  2016-08-21  1:04  4%       ` John Smith
  1 sibling, 1 reply; 200+ results
From: Jeffrey R. Carter @ 2016-08-21  0:50 UTC (permalink / raw)


On 08/20/2016 05:01 PM, John Smith wrote:
> 
> Hi, I do have an Ada.Integer_Text_IO.Get above this call (some ways above it.)
> 
> How can I clear out that line terminator?  Another call to Get_Line, but not save the input?

The way to skip the next line terminator in an input file is with a call to
Skip_Line.

However, when using Text_IO for input from standard input, it's best to always
input an entire line at a time into a String, and then deal with the line in the
String. The fact that Get leaves a line terminator in the buffer wreaks havoc on
error handling.

Get_Speed : loop
   Ada.Text_IO.Put (Item => "Enter desired speed: ");

   Speed_Line : declare
      Line : constant String := Ada.Text_IO.Get_Line;

      Last : Natural;
   begin -- Speed_Line
      Speed_IO.Get (From => Line, Item => Speed, Last => Last);

      exit Get_Speed;
   exception -- Speed_Line
   when others =>
      Ada.Text_IO.Put_Line (Item => "Enter a valid speed.");
   end Speed_Line;
end loop Get_Speed;

-- 
Jeff Carter
"People called Romanes, they go the house?"
Monty Python's Life of Brian
79

^ permalink raw reply	[relevance 0%]

* Re: Why does this input get "skipped"?
  2016-08-21  0:01  4%   ` John Smith
@ 2016-08-21  0:36  0%     ` John Smith
  2016-08-21  0:50  0%     ` Jeffrey R. Carter
  1 sibling, 0 replies; 200+ results
From: John Smith @ 2016-08-21  0:36 UTC (permalink / raw)


On Saturday, August 20, 2016 at 8:01:16 PM UTC-4, John Smith wrote:
> On Saturday, August 20, 2016 at 7:16:39 PM UTC-4, Jeffrey R. Carter wrote:
> > On 08/20/2016 03:41 PM, John Smith wrote:
> > > This is the snippet in question:
> > > Ada.Text_IO.Put("Delete a value - > ");
> > > String_Input := Ada.Text_IO.Unbounded_IO.Get_Line;
> > > Ada.Text_IO.New_Line;
> > > 
> > > The purpose is to have the user enter some string and then keep going.  When I ran the above code, I found that I saw "Delete a value - > " being printed, but the program didn't even give me a chance to enter some form of text...
> > > 
> > > Why did my code keep running?
> > 
> > It's impossible to be sure from the little information given, but the most
> > likely explanation is that there was already a line terminator waiting to be
> > consumed, and the call to Get_Line consumed it (and any characters preceding
> > it). This is often the case after a call to something like Ada.Integer_Text_IO.Get.
> > 
> > -- 
> > Jeff Carter
> > "People called Romanes, they go the house?"
> > Monty Python's Life of Brian
> > 79
> 
> Hi, I do have an Ada.Integer_Text_IO.Get above this call (some ways above it.)
> 
> How can I clear out that line terminator?  Another call to Get_Line, but not save the input?

Adding a Get_Line right after the Integer_Text_IO.Get did get me the result that I want.  However, why does this feel like a kludge?


^ permalink raw reply	[relevance 0%]

* Re: Why does this input get "skipped"?
  2016-08-20 23:16  4% ` Jeffrey R. Carter
@ 2016-08-21  0:01  4%   ` John Smith
  2016-08-21  0:36  0%     ` John Smith
  2016-08-21  0:50  0%     ` Jeffrey R. Carter
  0 siblings, 2 replies; 200+ results
From: John Smith @ 2016-08-21  0:01 UTC (permalink / raw)


On Saturday, August 20, 2016 at 7:16:39 PM UTC-4, Jeffrey R. Carter wrote:
> On 08/20/2016 03:41 PM, John Smith wrote:
> > This is the snippet in question:
> > Ada.Text_IO.Put("Delete a value - > ");
> > String_Input := Ada.Text_IO.Unbounded_IO.Get_Line;
> > Ada.Text_IO.New_Line;
> > 
> > The purpose is to have the user enter some string and then keep going.  When I ran the above code, I found that I saw "Delete a value - > " being printed, but the program didn't even give me a chance to enter some form of text...
> > 
> > Why did my code keep running?
> 
> It's impossible to be sure from the little information given, but the most
> likely explanation is that there was already a line terminator waiting to be
> consumed, and the call to Get_Line consumed it (and any characters preceding
> it). This is often the case after a call to something like Ada.Integer_Text_IO.Get.
> 
> -- 
> Jeff Carter
> "People called Romanes, they go the house?"
> Monty Python's Life of Brian
> 79

Hi, I do have an Ada.Integer_Text_IO.Get above this call (some ways above it.)

How can I clear out that line terminator?  Another call to Get_Line, but not save the input?

^ permalink raw reply	[relevance 4%]

* Re: Why does this input get "skipped"?
  @ 2016-08-20 23:16  4% ` Jeffrey R. Carter
  2016-08-21  0:01  4%   ` John Smith
  0 siblings, 1 reply; 200+ results
From: Jeffrey R. Carter @ 2016-08-20 23:16 UTC (permalink / raw)


On 08/20/2016 03:41 PM, John Smith wrote:
> This is the snippet in question:
> Ada.Text_IO.Put("Delete a value - > ");
> String_Input := Ada.Text_IO.Unbounded_IO.Get_Line;
> Ada.Text_IO.New_Line;
> 
> The purpose is to have the user enter some string and then keep going.  When I ran the above code, I found that I saw "Delete a value - > " being printed, but the program didn't even give me a chance to enter some form of text...
> 
> Why did my code keep running?

It's impossible to be sure from the little information given, but the most
likely explanation is that there was already a line terminator waiting to be
consumed, and the call to Get_Line consumed it (and any characters preceding
it). This is often the case after a call to something like Ada.Integer_Text_IO.Get.

-- 
Jeff Carter
"People called Romanes, they go the house?"
Monty Python's Life of Brian
79


^ permalink raw reply	[relevance 4%]

* Re: Ada.Strings.Fixed.Count raises Storage_Error
  2016-06-26 21:18  0%   ` Victor Porton
@ 2016-06-27 12:52  0%     ` Victor Porton
  0 siblings, 0 replies; 200+ results
From: Victor Porton @ 2016-06-27 12:52 UTC (permalink / raw)


I've reported the bug:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71674

Victor Porton wrote:
> GNAT 6.1.1 on Debian Linux "testing":
> 
> $ ./test_count
>           0          1
> 
> raised STORAGE_ERROR : stack overflow or erroneous memory access
> 
> Let's decide who of us will report the bug, so that the report won't
> happen to be duplicate?
> 
> Georg Bauhaus wrote:
>> On 12.05.16 13:36, Xavier Petit wrote:
>> 
>>> with Ada.Strings.Fixed, Ada.Integer_Text_IO;
>>> use  Ada.Strings.Fixed, Ada.Integer_Text_IO;
>>>
>>> procedure Test_Count is
>>>     S : constant String (Positive'Last - 2 .. Positive'Last) := "Ada";
>>> begin
>>>     Put (Count (Source => S,                         Pattern => "AA"));
>>>     Put (Count (Source => S (S'First .. S'Last - 1), Pattern => "A"));
>>>     Put (Count (Source => S,                         Pattern => "A"));
>>> end;
>>>
>>> Output on gnat-gcc 5.3.1 :
>>>
>>>            0          1
>>>
>>> raised STORAGE_ERROR : stack overflow or erroneous memory access
>> 
>> Compiling such that the RTS is recompiled will result in
>> 
>> raised CONSTRAINT_ERROR : a-strsea.adb:102 overflow check failed
>> 
>> The message points at a line in the implementation of
>> Ada.Strings.Search.Count, for the third of the calls. It reads
>> 
>>       Ind := Ind + 1;
>> 
>> where Ind looks seems to be go along with the Index of your S,
>> IINM. Effectively (PL1 = Pattern'Length - 1 being 0), then loop
>> there boils down to this:
>> 
>>     while Ind <= Source'Last loop
>>        if Pattern = Source (Ind .. Ind) then
>>           ...
>>        else
>>           Ind := Ind + 1;
>>        end if;
>>     end loop;
>> 
>> And this would explains the overflow.
>> 
>> Just the slip-up that Ada subtypes were designed to help prevent?
>> 
>> 
-- 
Victor Porton - http://portonvictor.org

^ permalink raw reply	[relevance 0%]

* Re: Ada.Strings.Fixed.Count raises Storage_Error
  2016-05-12 22:05  0% ` Georg Bauhaus
@ 2016-06-26 21:18  0%   ` Victor Porton
  2016-06-27 12:52  0%     ` Victor Porton
  0 siblings, 1 reply; 200+ results
From: Victor Porton @ 2016-06-26 21:18 UTC (permalink / raw)


GNAT 6.1.1 on Debian Linux "testing":

$ ./test_count 
          0          1

raised STORAGE_ERROR : stack overflow or erroneous memory access

Let's decide who of us will report the bug, so that the report won't happen 
to be duplicate?

Georg Bauhaus wrote:
> On 12.05.16 13:36, Xavier Petit wrote:
> 
>> with Ada.Strings.Fixed, Ada.Integer_Text_IO;
>> use  Ada.Strings.Fixed, Ada.Integer_Text_IO;
>>
>> procedure Test_Count is
>>     S : constant String (Positive'Last - 2 .. Positive'Last) := "Ada";
>> begin
>>     Put (Count (Source => S,                         Pattern => "AA"));
>>     Put (Count (Source => S (S'First .. S'Last - 1), Pattern => "A"));
>>     Put (Count (Source => S,                         Pattern => "A"));
>> end;
>>
>> Output on gnat-gcc 5.3.1 :
>>
>>            0          1
>>
>> raised STORAGE_ERROR : stack overflow or erroneous memory access
> 
> Compiling such that the RTS is recompiled will result in
> 
> raised CONSTRAINT_ERROR : a-strsea.adb:102 overflow check failed
> 
> The message points at a line in the implementation of
> Ada.Strings.Search.Count, for the third of the calls. It reads
> 
>       Ind := Ind + 1;
> 
> where Ind looks seems to be go along with the Index of your S,
> IINM. Effectively (PL1 = Pattern'Length - 1 being 0), then loop
> there boils down to this:
> 
>     while Ind <= Source'Last loop
>        if Pattern = Source (Ind .. Ind) then
>           ...
>        else
>           Ind := Ind + 1;
>        end if;
>     end loop;
> 
> And this would explains the overflow.
> 
> Just the slip-up that Ada subtypes were designed to help prevent?
> 
> 
-- 
Victor Porton - http://portonvictor.org


^ permalink raw reply	[relevance 0%]

* Re: Generic Embedded List Nodes
  @ 2016-06-23  8:19  2%                                   ` Niklas Holsti
  0 siblings, 0 replies; 200+ results
From: Niklas Holsti @ 2016-06-23  8:19 UTC (permalink / raw)


On 16-06-23 05:12 , Warren wrote:
> On Tuesday, 21 June 2016 17:38:36 UTC-4, Niklas Holsti  wrote:
> ...
>>     type Emb_Node_T is tagged;
>>
>>     type Emb_Node_Ref_T is access all Emb_Node_T'Class;
>>
>>     type Emb_Node_T is tagged record
>>        Prev, Next : Emb_Node_Ref_T;
>>        -- Prev and Next are null if the node is not in any list.
>>        -- When the node is first in a list, Prev points to the list head.
>>        -- When the node is last in a list, Next is null.
>>     end record;
>>
>>     subtype List_T is Emb_Node_T;
>>     -- A list head.
>>     -- Next points to the first node in the list.
>>     -- Prev is null.
> ...
>
> The insertion, traversal and deletes are generally no problem. The problem
> occurs when traversing to access the object.

Indeed I left out an example of traversal, sorry.

> Let's say you have a list of  timed out sockets (in pseudo code):
>
> node := head.next;
> while node /= null loop
>     next_node := node.next;
>     -- now access the object holding "node" so that it can be freed
>     node.unlink;
>     Free(node's object);
>     node := node_next;

(You surely meant next_node, above.)

> end loop;
>
> I keep bumping back into this Ada compiler restriction, which is
> maddening. It doesn't seem easily fooled.

That's the reason for having the derived descendants of Emb_Node_T, with 
the access discriminants. In my example, the discriminant Obj of an 
embedded Integer_Emb_Node_T points to the enclosing Integer_Object_T. 
Here is the relevant part of the example; to place it in the context of 
your example, above, imagine that Integer_Object_T is a potentially 
"time out socket":

    type Integer_Object_T;

    type Integer_Emb_Node_T (Obj : access Integer_Object_T)
    is new Emb_Node_T with null record;
    -- (Explanation added:) Obj accesses the Integer_Object_T
    -- which contains this Integer_Emb_Node_T.

    type Integer_Object_T is limited record
       Value : Integer;
       Node1 : aliased Integer_Emb_Node_T (Integer_Object_T'Access);
       Node2 : aliased Integer_Emb_Node_T (Integer_Object_T'Access);
    end record;

The Obj pointers are set automatically by the expressions 
Integer_Object_T'Access, which access the current instance of 
Integer_Object_T.

Here's a procedure to print out the Value components of all 
Integer_Object_T elements in a list of such elements:

    procedure Print_Integer_Values (List : in List_T'Class)
    is
       Node : Emb_Node_Ref_T := List.Next;
    begin
       while Node /= null loop
          if Node.all in Integer_Emb_Node_T'Class then
             Ada.Integer_Text_IO.Put (
                Integer_Emb_Node_T (Node.all).Obj.Value);
          end if;
          Node := Node.Next;
       end loop;
    end Print_Values;

(Compiled, not tested.)

By the way, the solution example I gave assumed that you want 
heterogeneous lists, in which any list can contain any type of object. 
That's why the above procedure Print_Integer_Values has to check if the 
current Node is an Integer_Obj_T before it can use the Obj discriminant 
to get to the object.

If you actually want homogeneous lists, in which any given list contains 
only elements of one and the same type, which corresponds to the type of 
the list head, I would drop the root type Emb_Node_T and define each 
embedded-node type separately from scratch. In this case a generic 
package to create doubly linked lists of a given type could be useful. 
If this is your preference, say it and I will make an example for you.

> I think the only simple way to do this in Ada, is to allocate
> a very large array of Access to record values, for each socket
> (I know what the max # of sockets are). The descriptors start at
> zero so this works well.

That would also work. Your choice, of course.

-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
       .      @       .


^ permalink raw reply	[relevance 2%]

* Re: Generic Embedded List Nodes
  2016-06-19 18:27  4%         ` Warren
@ 2016-06-19 19:04  0%           ` Dmitry A. Kazakov
    0 siblings, 1 reply; 200+ results
From: Dmitry A. Kazakov @ 2016-06-19 19:04 UTC (permalink / raw)


On 2016-06-19 20:27, Warren wrote:
> On Sunday, 19 June 2016 00:45:54 UTC-4, Simon Wright  wrote:
>> Warren <ve3wwg@gmail.com> writes:
>>
>>    type Node_Type(Obj: access Object_Type) is new Emb_Node
>>      with null record;
>
> I've come to the conclusion that my original idea in Ada terms is too half baked.
>
> What it will come down to in the end is doing an offset calculation
> from the Node back to the Object when its access is required (through a
> function).
>
> Even in C/C++ this is a bit of a problem. While there is an
> offsetof(type,member) macro, this is only usable on non-dynamic types.
> Calculating an offset of a struct is trivial when you have it allocated.
> But when the class has a constructor, then you may not want to invoke
> that overhead only to create one for offset calculations.
>
> In Ada for some record Type R.M where R is the record and M is the
> member, you cannot do R.M'Position when R is just a type. But you can
> cheat this, similar to how I have done it in C/C++:
>
> with System;
> with Ada.Integer_Text_IO;
>
> procedure T is
>    use Ada.Integer_Text_IO;
>
>    type R_Type is
>       record
>          I : Integer;
>          F : Float;
>       end record;
>
>    A:    System.Address;
>
>    R:    R_Type;
>    for R'Address use A;
>
> begin
>    Put(R.I'Position);
>    Put(R.F'Position);
> end;
>
> This never allocates the object, but assumes it already exists at
> address A.. Since the record and its members are never actually used, it
> is possible to have the compiler do the necessary calculations. This
> will complain "warning: variable "A" is read but never assigned", however.
>
> I suppose a tagged R.Initialize could also establish an 'Access value
> in all Emb_Node members, using some other procedure call for Emb_Node
> (perhaps Set_Object). But it is desireable not to have to carry the
> object reference in the Emb_Node at all.

Maybe I don't understand the problem, but it seems you want externally 
linked objects that themselves were of any type. The best way to do it 
is IMO a custom memory pool.

My implementation of linked list uses this approach.

http://www.dmitry-kazakov.de/ada/components.htm#Generic_Doubly_Linked_Web

The object is allocated in the custom pool, which actually takes memory 
from another, e.g. standard, pool. But before that adds links just in 
front of the object. The pool-specific pointer carries the operations 
Next, Previous etc. Yes, it uses address arithmetic to get to the links, 
but no record member offsets or other crazy stuff because you deal with 
pointers to the objects, not the pointers to the list elements.

The only problem you must be aware of is that X'Address attribute is 
broken in Ada when X is an array:

    X'Address = X (X'First)'Address

which if of course not the address of the array. If you are going to 
instantiate your package with an array type, you must calculate the 
offset to the array object beginning.

-- 
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de

^ permalink raw reply	[relevance 0%]

* Re: Generic Embedded List Nodes
  @ 2016-06-19 18:27  4%         ` Warren
  2016-06-19 19:04  0%           ` Dmitry A. Kazakov
  0 siblings, 1 reply; 200+ results
From: Warren @ 2016-06-19 18:27 UTC (permalink / raw)


On Sunday, 19 June 2016 00:45:54 UTC-4, Simon Wright  wrote:
> Warren <ve3wwg@gmail.com> writes:
> 
>    type Node_Type(Obj: access Object_Type) is new Emb_Node
>      with null record;

I've come to the conclusion that my original idea in Ada terms is too half baked. 

What it will come down to in the end is doing an offset calculation from the Node back to the Object when its access is required (through a function). 

Even in C/C++ this is a bit of a problem. While there is an offsetof(type,member) macro, this is only usable on non-dynamic types. Calculating an offset of a struct is trivial when you have it allocated. But when the class has a constructor, then you may not want to invoke that overhead only to create one for offset calculations.

In Ada for some record Type R.M where R is the record and M is the member, you cannot do R.M'Position when R is just a type. But you can cheat this, similar to how I have done it in C/C++:

with System;
with Ada.Integer_Text_IO;

procedure T is
   use Ada.Integer_Text_IO;

   type R_Type is
      record
         I : Integer;
         F : Float;
      end record;

   A:    System.Address;

   R:    R_Type;
   for R'Address use A;
   
begin
   Put(R.I'Position);
   Put(R.F'Position);
end;

This never allocates the object, but assumes it already exists at address A. Since the record and its members are never actually used, it is possible to have the compiler do the necessary calculations. This will complain "warning: variable "A" is read but never assigned", however.

I suppose a tagged R.Initialize could also establish an 'Access value in all Emb_Node members, using some other procedure call for Emb_Node (perhaps Set_Object). But it is desireable not to have to carry the object reference in the Emb_Node at all.

Warren

^ permalink raw reply	[relevance 4%]

* Re: Ada.Strings.Fixed.Count raises Storage_Error
  2016-05-12 11:36  5% Ada.Strings.Fixed.Count raises Storage_Error Xavier Petit
  2016-05-12 15:22  0% ` Tero Koskinen
  2016-05-12 22:05  0% ` Georg Bauhaus
@ 2016-05-12 22:56  0% ` Randy Brukardt
  2 siblings, 0 replies; 200+ results
From: Randy Brukardt @ 2016-05-12 22:56 UTC (permalink / raw)


Well, *anything* in Ada is allowed to raise Storage_Error (even the null 
statement!), so formally the behavior is correct.

OTOH, there doesn't seem to be any actual running out of memory here, so it 
is most likely a bug (especially as the other responses suggest that the 
main problem is that the checks are suppressed in the library code). And 
it's unlikely that the implementer expected this code to raise 
Storage_Error.

                            Randy.

"Xavier Petit" <xpetit@becoast.fr> wrote in message 
news:57346ac8$0$4570$426a74cc@news.free.fr...
> Hello, I would like to know if it is normal or a known bug.
>
> function Count
>   (Source  : String;
>    Pattern : String;
>    Mapping : Maps.Character_Mapping := Maps.Identity) return Natural;
>
> When Source'Last = Positive'Last and Pattern'Length = 1, I get
> Storage_Error, it seems this is because the checks are suppressed in
> this GNAT runtime function ? So with checks it would result a
> Constraint_Error ?
>
> Internally, the exit condition is tested after the index incrementation, 
> so in this specific case the "Ind" index tries to store Positive'Last + 1. 
> I think.
>
> Here the code :
>
> with Ada.Strings.Fixed, Ada.Integer_Text_IO;
> use  Ada.Strings.Fixed, Ada.Integer_Text_IO;
>
> procedure Test_Count is
>    S : constant String (Positive'Last - 2 .. Positive'Last) := "Ada";
> begin
>    Put (Count (Source => S,                         Pattern => "AA"));
>    Put (Count (Source => S (S'First .. S'Last - 1), Pattern => "A"));
>    Put (Count (Source => S,                         Pattern => "A"));
> end;
>
> Output on gnat-gcc 5.3.1 :
>
>           0          1
>
> raised STORAGE_ERROR : stack overflow or erroneous memory access
>
>
> Thanks by advance
>
> -- 
> Xavier Petit 



^ permalink raw reply	[relevance 0%]

* Re: Ada.Strings.Fixed.Count raises Storage_Error
  2016-05-12 11:36  5% Ada.Strings.Fixed.Count raises Storage_Error Xavier Petit
  2016-05-12 15:22  0% ` Tero Koskinen
@ 2016-05-12 22:05  0% ` Georg Bauhaus
  2016-06-26 21:18  0%   ` Victor Porton
  2016-05-12 22:56  0% ` Randy Brukardt
  2 siblings, 1 reply; 200+ results
From: Georg Bauhaus @ 2016-05-12 22:05 UTC (permalink / raw)


On 12.05.16 13:36, Xavier Petit wrote:

> with Ada.Strings.Fixed, Ada.Integer_Text_IO;
> use  Ada.Strings.Fixed, Ada.Integer_Text_IO;
>
> procedure Test_Count is
>     S : constant String (Positive'Last - 2 .. Positive'Last) := "Ada";
> begin
>     Put (Count (Source => S,                         Pattern => "AA"));
>     Put (Count (Source => S (S'First .. S'Last - 1), Pattern => "A"));
>     Put (Count (Source => S,                         Pattern => "A"));
> end;
>
> Output on gnat-gcc 5.3.1 :
>
>            0          1
>
> raised STORAGE_ERROR : stack overflow or erroneous memory access

Compiling such that the RTS is recompiled will result in

raised CONSTRAINT_ERROR : a-strsea.adb:102 overflow check failed

The message points at a line in the implementation of
Ada.Strings.Search.Count, for the third of the calls. It reads

      Ind := Ind + 1;

where Ind looks seems to be go along with the Index of your S,
IINM. Effectively (PL1 = Pattern'Length - 1 being 0), then loop
there boils down to this:

    while Ind <= Source'Last loop
       if Pattern = Source (Ind .. Ind) then
          ...
       else
          Ind := Ind + 1;
       end if;
    end loop;

And this would explains the overflow.

Just the slip-up that Ada subtypes were designed to help prevent?


-- 
"HOTDOGS ARE NOT BOOKMARKS"
Springfield Elementary teaching staff

^ permalink raw reply	[relevance 0%]

* Re: Ada.Strings.Fixed.Count raises Storage_Error
  2016-05-12 11:36  5% Ada.Strings.Fixed.Count raises Storage_Error Xavier Petit
@ 2016-05-12 15:22  0% ` Tero Koskinen
  2016-05-12 22:05  0% ` Georg Bauhaus
  2016-05-12 22:56  0% ` Randy Brukardt
  2 siblings, 0 replies; 200+ results
From: Tero Koskinen @ 2016-05-12 15:22 UTC (permalink / raw)


Hi,

12.5.2016, 14.36, Xavier Petit wrote:
> Hello, I would like to know if it is normal or a known bug.
>
> function Count
>    (Source  : String;
>     Pattern : String;
>     Mapping : Maps.Character_Mapping := Maps.Identity) return Natural;
>
> When Source'Last = Positive'Last and Pattern'Length = 1, I get
> Storage_Error, it seems this is because the checks are suppressed in
> this GNAT runtime function ? So with checks it would result a
> Constraint_Error ?
...
>
> Here the code :
>
> with Ada.Strings.Fixed, Ada.Integer_Text_IO;
> use  Ada.Strings.Fixed, Ada.Integer_Text_IO;
>
> procedure Test_Count is
>     S : constant String (Positive'Last - 2 .. Positive'Last) := "Ada";
> begin
>     Put (Count (Source => S,                         Pattern => "AA"));
>     Put (Count (Source => S (S'First .. S'Last - 1), Pattern => "A"));
>     Put (Count (Source => S,                         Pattern => "A"));
> end;
>
> Output on gnat-gcc 5.3.1 :
>
>            0          1
>
> raised STORAGE_ERROR : stack overflow or erroneous memory access

When compiled with Janus/Ada the output is following:
C:\Work\xavier-fixed-count\obj> test_cou
      0     1     1
C:\Work\xavier-fixed-count\obj>

I would say that Janus/Ada is correct here and you have found a bug from 
GNAT.


>
> Thanks by advance
>

Yours,
  Tero


^ permalink raw reply	[relevance 0%]

* Ada.Strings.Fixed.Count raises Storage_Error
@ 2016-05-12 11:36  5% Xavier Petit
  2016-05-12 15:22  0% ` Tero Koskinen
                   ` (2 more replies)
  0 siblings, 3 replies; 200+ results
From: Xavier Petit @ 2016-05-12 11:36 UTC (permalink / raw)


Hello, I would like to know if it is normal or a known bug.

function Count
   (Source  : String;
    Pattern : String;
    Mapping : Maps.Character_Mapping := Maps.Identity) return Natural;

When Source'Last = Positive'Last and Pattern'Length = 1, I get
Storage_Error, it seems this is because the checks are suppressed in
this GNAT runtime function ? So with checks it would result a
Constraint_Error ?

Internally, the exit condition is tested after the index incrementation, 
so in this specific case the “Ind” index tries to store Positive'Last + 
1. I think.

Here the code :

with Ada.Strings.Fixed, Ada.Integer_Text_IO;
use  Ada.Strings.Fixed, Ada.Integer_Text_IO;

procedure Test_Count is
    S : constant String (Positive'Last - 2 .. Positive'Last) := "Ada";
begin
    Put (Count (Source => S,                         Pattern => "AA"));
    Put (Count (Source => S (S'First .. S'Last - 1), Pattern => "A"));
    Put (Count (Source => S,                         Pattern => "A"));
end;

Output on gnat-gcc 5.3.1 :

           0          1

raised STORAGE_ERROR : stack overflow or erroneous memory access


Thanks by advance

-- 
Xavier Petit

^ permalink raw reply	[relevance 5%]

* Re: How to get a 2D arrays range?
  2015-11-22  3:31  4% How to get a 2D arrays range? John Smith
@ 2015-11-22  7:09  0% ` Niklas Holsti
  0 siblings, 0 replies; 200+ results
From: Niklas Holsti @ 2015-11-22  7:09 UTC (permalink / raw)


On 15-11-22 05:31 , John Smith wrote:
> Hello,
>
> I have an array of integers, like so:
>
> ArrayInteger : array (1 .. 10, 1 .. 10) of Integer;
> ...
> ArrayInteger := (others => (others => 0));
> ...
> for iterA in ArrayInteger'Range loop
>    for iterB in 1 .. 10 loop
>      Ada.Integer_Text_IO.Put(ArrayInteger(iterA, iterB));
>    end loop;
>
>    Ada.Text_IO.New_Line;
> end loop;
>
> Of the nested for-loop, where I explicitly call out 1 .. 10, I'd like to specify
> the range more dynamically.  How can I do this?
>
> I tried ArrayInteger(0)'Range, with no success...

Try ArrayInteger'Range(2).

For an N-dimensional array A, A'Range(N) gives the range of the N'th 
dimension. Dimensions are numbered starting from 1.

This is described in RM 3.6.2.

For a multi-dimensional array A, the plain A'Range is equivalent to 
A'Range(1) and gives the range of the first dimension.

For clarity, I would write the outer loop with ArrayInteger'Range(1), 
not the plain 'Range although it means the same, and the inner loop of 
course with ArrayInteger'Range(2).

Your ArrayInteger is a 2-dimensional array, so the expression 
ArrayInteger(0), with a single index, is invalid; an N-dimensional array 
always (in Ada) requires N indices. (Also, zero is not even a valid 
index for either dimension of your array, because the indices start from 1.)

It is of course possible to define a two-dimensional set of numbers as a 
one-dimensional array of "rows", where each row is a one-dimensional 
array of numbers, but for that you must define the row-type as a named type.

-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
       .      @       .

^ permalink raw reply	[relevance 0%]

* How to get a 2D arrays range?
@ 2015-11-22  3:31  4% John Smith
  2015-11-22  7:09  0% ` Niklas Holsti
  0 siblings, 1 reply; 200+ results
From: John Smith @ 2015-11-22  3:31 UTC (permalink / raw)


Hello,

I have an array of integers, like so:

ArrayInteger : array (1 .. 10, 1 .. 10) of Integer;
...
ArrayInteger := (others => (others => 0));
...
for iterA in ArrayInteger'Range loop
  for iterB in 1 .. 10 loop
    Ada.Integer_Text_IO.Put(ArrayInteger(iterA, iterB));
  end loop;

  Ada.Text_IO.New_Line;
end loop;

Of the nested for-loop, where I explicitly call out 1 .. 10, I'd like to specify 
the range more dynamically.  How can I do this?

I tried ArrayInteger(0)'Range, with no success...


^ permalink raw reply	[relevance 4%]

* Re: If not Ada, what else...
  2015-08-23 17:18  0%                         ` Jeffrey R. Carter
@ 2015-08-23 17:31  0%                           ` Waldek Hebisch
  0 siblings, 0 replies; 200+ results
From: Waldek Hebisch @ 2015-08-23 17:31 UTC (permalink / raw)


Jeffrey R. Carter <spam.jrcarter.not@spam.not.acm.org> wrote:
> On 08/23/2015 09:26 AM, Waldek Hebisch wrote:
> > 
> > with Ada.Integer_Text_IO;    --  1  10.1.2, A.10 Context clause
> > procedure  hamming is
> > n0 : constant integer := 1_691;
> > buff : array(1..n0) of Integer;
> > procedure hamn(n : Integer) is
> 
> N is unreferenced.

Oops, my editor messed formatting.  Fixing formatting I lost
a line (of course now formatting needs to be fixed again...).
> >     cand : array(1..3) of Integer;
> >     ind : array(1..3) of Integer := (1, 1, 1);
> >     p : array(1..3) of Integer := (2, 3, 5);
> >     cmin : Integer;
> >     begin
> >         buff(1) := 1;
            for i in 2..n loop
> >         for j in 1..3 loop cand(j) := p(j)*buff(ind(j)); end loop;
> >         cmin := cand(1);
> >         for j in 2..3 loop
> >                 if cand(j) < cmin then cmin := cand(j); end if;
> >         end loop;
> >         buff(i) := cmin;
> 
> I is not defined.
> 
> >         for j in 1..3 loop
> >             if cand(j) = cmin then ind(j) := ind(j) + 1; end if;
> >         end loop;
> >     end loop;
> 
> No matching "loop" for this "end loop;"
> 
> > end hamn;
> > 
> > begin
> >    hamn(n0);
> >    for i in 1..10 loop
> >        Ada.Integer_Text_IO.put(buff(i));
> >    end loop;
> >    Ada.Integer_Text_IO.put(buff(n0));
> > end hamming;
> 

-- 
                              Waldek Hebisch
hebisch@math.uni.wroc.pl 


^ permalink raw reply	[relevance 0%]

* Re: If not Ada, what else...
  2015-08-23 16:26  5%                       ` Waldek Hebisch
@ 2015-08-23 17:18  0%                         ` Jeffrey R. Carter
  2015-08-23 17:31  0%                           ` Waldek Hebisch
  0 siblings, 1 reply; 200+ results
From: Jeffrey R. Carter @ 2015-08-23 17:18 UTC (permalink / raw)


On 08/23/2015 09:26 AM, Waldek Hebisch wrote:
> 
> with Ada.Integer_Text_IO;    --  1  10.1.2, A.10 Context clause
> procedure  hamming is
> n0 : constant integer := 1_691;
> buff : array(1..n0) of Integer;
> procedure hamn(n : Integer) is

N is unreferenced.

>     cand : array(1..3) of Integer;
>     ind : array(1..3) of Integer := (1, 1, 1);
>     p : array(1..3) of Integer := (2, 3, 5);
>     cmin : Integer;
>     begin
>         buff(1) := 1;
>         for j in 1..3 loop cand(j) := p(j)*buff(ind(j)); end loop;
>         cmin := cand(1);
>         for j in 2..3 loop
>                 if cand(j) < cmin then cmin := cand(j); end if;
>         end loop;
>         buff(i) := cmin;

I is not defined.

>         for j in 1..3 loop
>             if cand(j) = cmin then ind(j) := ind(j) + 1; end if;
>         end loop;
>     end loop;

No matching "loop" for this "end loop;"

> end hamn;
> 
> begin
>    hamn(n0);
>    for i in 1..10 loop
>        Ada.Integer_Text_IO.put(buff(i));
>    end loop;
>    Ada.Integer_Text_IO.put(buff(n0));
> end hamming;

-- 
Jeff Carter
"I blow my nose on you."
Monty Python & the Holy Grail
03


^ permalink raw reply	[relevance 0%]

* Re: If not Ada, what else...
  @ 2015-08-23 16:26  5%                       ` Waldek Hebisch
  2015-08-23 17:18  0%                         ` Jeffrey R. Carter
  0 siblings, 1 reply; 200+ results
From: Waldek Hebisch @ 2015-08-23 16:26 UTC (permalink / raw)


Paul Rubin <no.email@nospam.invalid> wrote:
> Waldek Hebisch <hebisch@antispam.uni.wroc.pl> writes:
> >> > http://rosettacode.org/wiki/Hamming_numbers#Ada
> > AFAICS iterative version which uses array as a stream buffer
> > is about 20 lines long and quite easy to write. 
> 
> I'd be interested in seeing what that looks like.  There's a Java
> version on rosettacode that uses priority queues and is somewhat messy.

See below: computational part has 19 lines, the rest is driver
to print result and a boilerplate.  This version is limited to
Integer size, need different type to get bigger size.  Number
of artitmetic operations is linear with n0, so with appripriate
numeric type could go to quite large n0.

with Ada.Integer_Text_IO;    --  1  10.1.2, A.10 Context clause
procedure  hamming is
n0 : constant integer := 1_691;
buff : array(1..n0) of Integer;
procedure hamn(n : Integer) is
    cand : array(1..3) of Integer;
    ind : array(1..3) of Integer := (1, 1, 1);
    p : array(1..3) of Integer := (2, 3, 5);
    cmin : Integer;
    begin
        buff(1) := 1;
        for j in 1..3 loop cand(j) := p(j)*buff(ind(j)); end loop;
        cmin := cand(1);
        for j in 2..3 loop
                if cand(j) < cmin then cmin := cand(j); end if;
        end loop;
        buff(i) := cmin;
        for j in 1..3 loop
            if cand(j) = cmin then ind(j) := ind(j) + 1; end if;
        end loop;
    end loop;
end hamn;

begin
   hamn(n0);
   for i in 1..10 loop
       Ada.Integer_Text_IO.put(buff(i));
   end loop;
   Ada.Integer_Text_IO.put(buff(n0));
end hamming;

-- 
                              Waldek Hebisch
hebisch@math.uni.wroc.pl 


^ permalink raw reply	[relevance 5%]

* Re: Error "exception not permitted here" when putting EXCEPTION in a loop
  2015-07-18 14:32  5%           ` Trish Cayetano
@ 2015-07-18 14:59  5%             ` Björn Lundin
  0 siblings, 0 replies; 200+ results
From: Björn Lundin @ 2015-07-18 14:59 UTC (permalink / raw)


On 2015-07-18 16:32, Trish Cayetano wrote:
> On Saturday, July 18, 2015 at 9:55:12 PM UTC+8, björn lundin wrote:

This one works.
As Tero said - skip_line in exception handler does it.
But you ONLY need it there.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
with Ada.IO_Exceptions; use Ada.IO_Exceptions;

procedure Main is
   GuessWord : String(1..20);
   last: Natural;
   option : Integer := 0;
   endGame: Boolean := False;
begin
    while not endGame loop
      begin
          Ada.Text_IO.Put_Line(" | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass
3)Enter Word 4)Exit ");
          Ada.Integer_Text_IO.Get(option);
          case option is
             when 1 =>
                Ada.Text_IO.Put_Line("Shuffle");
             when 2 =>
                Ada.Text_IO.Put_Line("Pass");
             when 3 =>
                Skip_Line; -- needed ????
                Ada.Text_IO.Put_Line("Enter word: ");
                Ada.Text_IO.Get_Line(GuessWord, Last);
             when 4 =>
                Ada.Text_IO.Put_Line("See you again soon!");
                endGame := true;
             when others =>
                Ada.Text_IO.Put_Line("Invalid Option");
          end case;
	exception
	  when ADA.IO_EXCEPTIONS.Data_Error =>
	    Ada.Text_IO.Put_Line ("Try a number from 1 to 4, Buddy");
	    skip_line;
         end;
     end loop;
end Main;

--
Björn

^ permalink raw reply	[relevance 5%]

* Re: Error "exception not permitted here" when putting EXCEPTION in a loop
  2015-07-18 13:56  4%         ` Björn Lundin
  2015-07-18 14:08  0%           ` Niklas Holsti
@ 2015-07-18 14:32  5%           ` Trish Cayetano
  2015-07-18 14:59  5%             ` Björn Lundin
  1 sibling, 1 reply; 200+ results
From: Trish Cayetano @ 2015-07-18 14:32 UTC (permalink / raw)


On Saturday, July 18, 2015 at 9:55:12 PM UTC+8, björn lundin wrote:
> On 2015-07-18 14:41, Trish Cayetano wrote:
> > Hello Björn, 
> > 
> > I don't need the inner loop after all.
> > I removed the inner loop but it still run in infinite loops.
> 
> it runs fine as long as you do not enter a non-digit.
> Then it seems like the call to
>   Ada.Integer_Text_IO.Get(option);
> does not clear the buffer.
> 
> if fed a character, Data_error is raised - which is correct.
> But the next time the code enters the loop, it seems it does
> not wait for input again.
> It raises the data_error again, and the infinite loop is there.
> 
> Seems like a compiler bug to me, but the behavior of *text_io.get
> has surprised me before.
> 
> --
> Björn

Well which reminds me! I added a SKIP_LINE... The expected output is close... It shows the exception error every other input... it waits for 2 inputs and then 1 input and then 2... 

REVISED

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
with Ada.IO_Exceptions; use Ada.IO_Exceptions;

procedure Main is

   GuessWord : String(1..20);
   last: Natural;

   option : Integer := 0;

   endGame: Boolean := False;


begin

    while not endGame loop


         begin

         Ada.Text_IO.Put_Line(" | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit ");
         Skip_Line;
         Ada.Integer_Text_IO.Get(option);
         
          exception
            when ADA.IO_EXCEPTIONS.Data_Error =>
            Ada.Text_IO.Put_Line ("Try a number from 1 to 4, Buddy");


      case option is
         when 1 =>
            Ada.Text_IO.Put_Line("Shuffle");
         when 2 =>
            Ada.Text_IO.Put_Line("Pass");
         when 3 =>
            Skip_Line;
            Ada.Text_IO.Put_Line("Enter word: ");
            Ada.Text_IO.Get_Line(GuessWord, Last);
         when 4 =>
            Ada.Text_IO.Put_Line("See you again soon!");
            endGame := true;
         when others =>
            Ada.Text_IO.Put_Line("Invalid Option");


      end case;

           
           



         end;

          end loop;



end Main;


=====

OUTPUT

C:\Users\a0284014\Desktop\ada\exception\obj\main
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
e
1
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
3
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
e
Try a number from 1 to 4, Buddy
Enter word: 
e
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
r
t
Try a number from 1 to 4, Buddy
Enter word: 
r
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
r

^ permalink raw reply	[relevance 5%]

* Re: Error "exception not permitted here" when putting EXCEPTION in a loop
  2015-07-18 13:56  4%         ` Björn Lundin
@ 2015-07-18 14:08  0%           ` Niklas Holsti
  2015-07-18 14:32  5%           ` Trish Cayetano
  1 sibling, 0 replies; 200+ results
From: Niklas Holsti @ 2015-07-18 14:08 UTC (permalink / raw)


On 15-07-18 16:56 , Björn Lundin wrote:
> On 2015-07-18 14:41, Trish Cayetano wrote:
>> Hello Björn,
>>
>> I don't need the inner loop after all.
>> I removed the inner loop but it still run in infinite loops.
>
> it runs fine as long as you do not enter a non-digit.
> Then it seems like the call to
>    Ada.Integer_Text_IO.Get(option);
> does not clear the buffer.
>
> if fed a character, Data_error is raised - which is correct.
> But the next time the code enters the loop, it seems it does
> not wait for input again.
> It raises the data_error again, and the infinite loop is there.
>
> Seems like a compiler bug to me, but the behavior of *text_io.get
> has surprised me before.

It is specified in the LRM that if the Get for Integer_IO encounters a 
character that cannot be part of the integer number, it stops at that 
point and does not "pass" that character. This means that one can read 
the integer 123 from the text "123ABC" and then read the string "ABC"; 
the Get for the integer does not "consume" the "A".

If you want to "clear the buffer", you should call Skip_Line, also in 
the exception handler.

-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
       .      @       .


^ permalink raw reply	[relevance 0%]

* Re: Error "exception not permitted here" when putting EXCEPTION in a loop
  2015-07-18 12:41  5%       ` Trish Cayetano
@ 2015-07-18 13:56  4%         ` Björn Lundin
  2015-07-18 14:08  0%           ` Niklas Holsti
  2015-07-18 14:32  5%           ` Trish Cayetano
  0 siblings, 2 replies; 200+ results
From: Björn Lundin @ 2015-07-18 13:56 UTC (permalink / raw)


On 2015-07-18 14:41, Trish Cayetano wrote:
> Hello Björn, 
> 
> I don't need the inner loop after all.
> I removed the inner loop but it still run in infinite loops.

it runs fine as long as you do not enter a non-digit.
Then it seems like the call to
  Ada.Integer_Text_IO.Get(option);
does not clear the buffer.

if fed a character, Data_error is raised - which is correct.
But the next time the code enters the loop, it seems it does
not wait for input again.
It raises the data_error again, and the infinite loop is there.

Seems like a compiler bug to me, but the behavior of *text_io.get
has surprised me before.

--
Björn


^ permalink raw reply	[relevance 4%]

* Re: Error "exception not permitted here" when putting EXCEPTION in a loop
  @ 2015-07-18 12:41  5%       ` Trish Cayetano
  2015-07-18 13:56  4%         ` Björn Lundin
  0 siblings, 1 reply; 200+ results
From: Trish Cayetano @ 2015-07-18 12:41 UTC (permalink / raw)


On Saturday, July 18, 2015 at 6:07:12 PM UTC+8, björn lundin wrote:
> On 2015-07-18 10:14, Trish Cayetano wrote:
> 
> e is my own code (i removed the functions and others)... S
> 
> orry I am really new to Ada. I actually tried also to put
> 
> another loop and added declare, begin and end. It
> 
> hang after I ran. And when I terminated the process, it looks like it
> ran infinitely in loops.
> > 
> 
> when you set endGame to true,
> you are in the *inner* loop.
> but the *outer* loop tests for endGame.
> 
> How do you exit the *inner* loop?
> 
> what purpose has the *inner* loop?
> 
> When you have the answer,
> your program will be easy to fix.
> 
> --
> Björn

Hello Björn, 

I don't need the inner loop after all.
I removed the inner loop but it still run in infinite loops.

REVISED CODE:

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
with Ada.IO_Exceptions; use Ada.IO_Exceptions;

procedure Main is

   GuessWord : String(1..20);
   last: Natural;

   option : Integer := 0;

   endGame: Boolean := False;


begin

    while not endGame loop


         begin

      Ada.Text_IO.Put_Line(" | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit ");
      Ada.Integer_Text_IO.Get(option);

      case option is
         when 1 =>
            Ada.Text_IO.Put_Line("Shuffle");
         when 2 =>
            Ada.Text_IO.Put_Line("Pass");
         when 3 =>
            Skip_Line;
            Ada.Text_IO.Put_Line("Enter word: ");
            Ada.Text_IO.Get_Line(GuessWord, Last);
         when 4 =>
            Ada.Text_IO.Put_Line("See you again soon!");
            endGame := true;
         when others =>
            Ada.Text_IO.Put_Line("Invalid Option");


      end case;

            Skip_Line;
            exception
            when ADA.IO_EXCEPTIONS.Data_Error =>
            Ada.Text_IO.Put_Line ("Try a number from 1 to 4, Buddy");
           



         end;
      
          end loop;



end Main;


RESULT:
C:\Users\a0284014\Desktop\ada\exception\obj\main
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
f
Try a number from 1 to 4, Buddy
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
Try a number from 1 to 4, Buddy
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
Try a number from 1 to 4, Buddy
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
Try a number from 1 to 4, Buddy
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
Try a number from 1 to 4, Buddy

[2015-07-18 20:39:33] process exited with status 1, elapsed time: 10.81s

^ permalink raw reply	[relevance 5%]

* Re: Error "exception not permitted here" when putting EXCEPTION in a loop
  @ 2015-07-18  8:14  5%   ` Trish Cayetano
    0 siblings, 1 reply; 200+ results
From: Trish Cayetano @ 2015-07-18  8:14 UTC (permalink / raw)


On Friday, July 17, 2015 at 11:58:18 PM UTC+8, G.B. wrote:
> On 17.07.15 17:47, Trish Cayetano wrote:
> > Hi,
> >
> > I am getting error "exception not permitted here" when running below in a loop.
> > Well it runs if I put it outside the loop but I need it inside the loop...
> >
> >             exception
> >              when ADA.IO_EXCEPTIONS.DATA_ERROR =>
> >              Ada.Text_IO.Put_Line ("Try a number from 1 to 4, Buddy");
> >
> > Thanks in advance for your help...
> >
> 
> does it look like
> 
>   loop
>      ...
>     exception ...
>      ...
>   end loop
> 
> If so, then note that "exception" must be in a block,
> such as a procedure body, or a block statement (LRM 5.6):
> 
> 
>    loop
>      begin
>        ...  -- handled sequence of statements
>      exception ...
>      ...
>      end;
>    end loop
> 
> More complete examples would help reducing guess work.

Thanks, David and GB.
It still does not work... 
Here is my own code (i removed the functions and others)... Sorry I am really new to Ada. I actually tried also to put another loop and added declare, begin and end. It hang after I ran. And when I terminated the process, it looks like it ran infinitely in loops. 

   
===== 
--start of code

   with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
with Ada.IO_Exceptions; use Ada.IO_Exceptions;

procedure Main is

   GuessWord : String(1..20);
   last: Natural;
 
   option : Integer := 0;
 
   endGame: Boolean := False;


begin

    while not endGame loop

      loop
         begin

      Ada.Text_IO.Put_Line(" | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit ");
      Ada.Integer_Text_IO.Get(option);

      case option is
         when 1 =>
            Ada.Text_IO.Put_Line("Shuffle");
         when 2 =>
            Ada.Text_IO.Put_Line("Pass");
         when 3 =>
            Skip_Line;
            Ada.Text_IO.Put_Line("Enter word: ");
            Ada.Text_IO.Get_Line(GuessWord, Last);
         when 4 =>
            Ada.Text_IO.Put_Line("See you again soon!");
            endGame := true;
         when others =>
            Ada.Text_IO.Put_Line("Invalid Option");


      end case;

            exception
            when ADA.IO_EXCEPTIONS.Data_Error =>
            Ada.Text_IO.Put_Line ("Try a number from 1 to 4, Buddy");




         end;
          end loop;
      end loop;


end Main;



--end of code
==============
RESULT:

C:\Users\a0284014\Desktop\ada\exception\obj\main
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
1
Shuffle
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
e
Try a number from 1 to 4, Buddy
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
Try a number from 1 to 4, Buddy
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
Try a number from 1 to 4, Buddy
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 
Try a number from 1 to 4, Buddy
 | CHOOSE YOUR OPTION: 1)Shuffle 2)Pass 3)Enter Word 4)Exit 

--retracted repeats
[2015-07-18 16:11:13] process exited with status 1, elapsed time: 19.58s

^ permalink raw reply	[relevance 5%]

* Re: After typing input of Integer it SKIPS getting the inputs of String.
  2015-07-11 15:14  5% After typing input of Integer it SKIPS getting the inputs of String Trish Cayetano
  2015-07-11 15:36  0% ` Niklas Holsti
@ 2015-07-11 18:05  4% ` Jeffrey R. Carter
  1 sibling, 0 replies; 200+ results
From: Jeffrey R. Carter @ 2015-07-11 18:05 UTC (permalink / raw)


On 07/11/2015 08:14 AM, Trish Cayetano wrote:
>    Put_Line("Enter Integer");
>    Get(inputNmbr,1);
>    Put_Line("Enter String");
>    Get_Line(inputText,StringNatural);
>    Put_Line("===================");
>    Put("Input for Integer: ");
>    Put(inputNmbr,1);
>    Put_Line("");
>    Put_Line("Input for String: ");
>    Put_Line(inputText(1..StringNatural));
> 
> Enter Integer
> 2
> Enter String
> ===================
> Input for Integer: 2
> Input for String: 

You don't say exactly what characters you input to get this, but I'm guessing
you typed

2<Enter>

A lot of people either don't read or don't understand the description of
Integer_IO.Get, which is at ARM A.10.8 (8-10)

http://www.adaic.org/resources/add_content/standards/12rm/html/RM-A-10-8.html

If you had, you'd expect exactly what you got.

It reads

8
If the value of the parameter Width is zero, skips any leading blanks, line
terminators, or page terminators, then reads a plus sign if present or (for a
signed type only) a minus sign if present, then reads the longest possible
sequence of characters matching the syntax of a numeric literal without a point.
If a nonzero value of Width is supplied, then exactly Width characters are
input, or the characters (possibly none) up to a line terminator, whichever
comes first; any skipped leading blanks are included in the count.
9
Returns, in the parameter Item, the value of type Num that corresponds to the
sequence input.
10/3
The exception Data_Error is propagated if the sequence of characters read does
not form a legal integer literal or if the value obtained is not of the subtype Num.

Note that it says nothing about skipping a line terminator. So if you wanted the
String to be "Hello", you'd have to type

2Hello<Enter>

The behavior of Get is especially interesting if you want to handle input errors:

Valid_Integer : loop
   Ada.Text_IO.Put (Item => "Enter an integer: ");

   Handle_Error : begin
      Ada.Integer_Text_IO.Get (Item => I);

      exit Valid_Integer;
   exception -- Handle_Error
   when others =>
      Ada.Text_IO.Put_Line (Item => "Invalid input. Try again.");
   end Handle_Error;
end loop Valid_Integer;

If the user accidentally types 'q' for the integer, this is an infinite loop,
because nothing ever reads the 'q'. For this reason, many of us like to read a
line into a String using Get_Line and parse it using the Get with a "From : in
String" parameter.

Valid_Integer : loop
   Ada.Text_IO.Put (Item => "Enter an integer: ");

   Handle_Error : declare
      Line : constant String := Ada.Text_IO.Get_Line;

      Last : Natural;
   begin -- Handle_Error
      Ada.Integer_Text_IO.Get (From => Line, Item => I, Last => Last);

      exit Valid_Integer;
   exception -- Handle_Error
   when others =>
      Ada.Text_IO.Put_Line (Item => "Invalid input. Try again.");
   end Handle_Error;
end loop Valid_Integer;

-- 
Jeff Carter
"How'd you like to hide the egg and gurgitate
a few saucers of mocha java?"
Never Give a Sucker an Even Break
101

^ permalink raw reply	[relevance 4%]

* Re: After typing input of Integer it SKIPS getting the inputs of String.
  2015-07-11 15:14  5% After typing input of Integer it SKIPS getting the inputs of String Trish Cayetano
@ 2015-07-11 15:36  0% ` Niklas Holsti
  2015-07-11 18:05  4% ` Jeffrey R. Carter
  1 sibling, 0 replies; 200+ results
From: Niklas Holsti @ 2015-07-11 15:36 UTC (permalink / raw)


Flip answer to "question" in Subject: Yes, it does. So what?

(That is, you could have been clearer about what you see as the problem, 
and what your question is.)

Better answer below:

On 15-07-11 18:14 , Trish Cayetano wrote:
> Code:
> with ada.Text_IO; use ada.Text_IO;
> with ada.Integer_Text_IO; use ada.Integer_Text_IO;
> procedure Main is
>
>
>     inputText: String (1..10);
>     inputNmbr : Integer;
>     StringNatural: Integer;
> begin
>
>     Put_Line("Enter Integer");
>     Get(inputNmbr,1);

The Get operation for integers leaves the "input point" after the last 
of the characters that form the integer. In this case, that point is 
before the "end of line" marker for that input line. If you then 
immediately call Get_Line, it will read characters up to the end-of-line 
marker, so it will return an empty string.

In your program, you evidently expect the Get_Line to start reading from 
the _next_ line after the line that contains the integer. So insert a 
Skip_Line between the Get(inputNmbr) and the Get_Line; that will pass 
the input point over the end-of-line so that the Get_Line starts reading 
from the start of the next line.

>     Put_Line("Enter String");
>     Get_Line(inputText,StringNatural);

-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
       .      @       .

^ permalink raw reply	[relevance 0%]

* After typing input of Integer it SKIPS getting the inputs of String.
@ 2015-07-11 15:14  5% Trish Cayetano
  2015-07-11 15:36  0% ` Niklas Holsti
  2015-07-11 18:05  4% ` Jeffrey R. Carter
  0 siblings, 2 replies; 200+ results
From: Trish Cayetano @ 2015-07-11 15:14 UTC (permalink / raw)


Code:
with ada.Text_IO; use ada.Text_IO;
with ada.Integer_Text_IO; use ada.Integer_Text_IO;
procedure Main is

    
   inputText: String (1..10);
   inputNmbr : Integer;
   StringNatural: Integer;  
begin
  
   Put_Line("Enter Integer");
   Get(inputNmbr,1);
   Put_Line("Enter String");
   Get_Line(inputText,StringNatural);
   Put_Line("===================");
   Put("Input for Integer: ");
   Put(inputNmbr,1);
   Put_Line("");
   Put_Line("Input for String: ");
   Put_Line(inputText(1..StringNatural));

end Main;

OUTPUT:

Enter Integer
2
Enter String
===================
Input for Integer: 2
Input for String: 


[2015-07-11 23:01:00] process terminated successfully, elapsed time: 00.86s

^ permalink raw reply	[relevance 5%]

* Re: How to shuffle/jumble letters of a given word?
  2015-06-30 12:29  5% ` Austin Obyrne
@ 2015-07-01 10:40  0%   ` darkestkhan
  0 siblings, 0 replies; 200+ results
From: darkestkhan @ 2015-07-01 10:40 UTC (permalink / raw)


On Tuesday, June 30, 2015 at 12:29:57 PM UTC, Austin Obyrne wrote:
> On Sunday, June 28, 2015 at 3:06:29 PM UTC+1, Trish Cayetano wrote:
> > I am creating a "text twist game" where you guess the words in a jumbled manner. How do I set the code to shuffle the letters? 
> > 
> > Example: word to be guessed is HELLO
> > 
> > What should be displayed is: LOLEH or LELHO
> > 
> > Thanks in advance!
> 
> There are 10 ways of shuffling 'Hello'
> 

Only 10 ways? I know 7 ways to do it, I suspect that there are many more. And if you meant that there are only "10 possible results of shuffling" then you are way off the target (5! possible shuffles, which is 120)

> The source code I posted earlier will copy 'n paste directly into your AdaGide editor for immediate running.
> 

What if someone doesn't have AdaGide editor? Why even assume that anyone has AdaGide editor?

> These results will often need some user-assistance but at least you can see what is available to you for your program.
>

Like providing different scrambling parameters each time he changes word?
 
> Also,
> 
> Herewith is a program that will calculate the scrambling parameters for you as general options to insert for 'Step' and 'Repeat' in your scrambling program
> 



> WITH Ada.Text_IO;
> WITH Ada.Integer_Text_IO;
> PROCEDURE Find_Scrambling_Parameters IS
> -------------------------------------------------------------------------
> --| This utility calculates the number of parameters that may be used
> --| to scramble a particular number in that many ways.
> --| Copyright © 2015 Austin O'Byrne.
> --| Last modified April 2015.
> -------------------------------------------------------------------------
>   SUM    : Integer;
>   Number : CONSTANT Integer:= 5; - - Number (Wordlength) for analysing as parameters
>   Line_Number: Integer;
>   View       : Character;
> 
> BEGIN  -- Find_Scrambling_Parameters
>     SUM := 0;
>     Line_Number:=0;
>     Ada.Text_IO.New_Line(2);
>     Ada.Text_IO.Put(Item => "                 Step     Times  Parameters space ");
>     Ada.Text_IO.New_Line(2);
>   FOR I in 1 .. Number LOOP
>     Line_Number := Line_Number + 1;
>     SUM := SUM + Number / I;
>     Ada.Integer_Text_IO.Put(Item => I, Width => 20);
>     Ada.Integer_Text_IO.Put(Item => Number/ I, Width => 10);
>     Ada.Integer_Text_IO.Put(Item => Sum, Width => 10);
>     Ada.Text_IO.New_Line;
>     IF Line_Number REM 50 = 0 THEN   --stalls program for viewing
>       Ada.Text_IO.Put(Item => "         ");
>       Ada.Text_IO.Put(Item => " - press any key/return to continue > ");
>       Ada.Text_IO.Get(Item => View);
>     END IF;
>   END LOOP;
> 
>      Ada.Text_IO.Put(Item => " There are ");
>      Ada.Integer_Text_IO.Put(Item => Sum, Width => 2);
>      Ada.Text_IO.Put(Item => " secret ways of scrambling this string of ciphertext. ");
> 
> 
> END Find_Scrambling_Parameters;
> 
> 

I checked this program and can't see what it has to do with shuffling at all.

Here is what your program basically does (after cutting out all the I/O routines)

Number : Integer := 5;
Sum: Integer := 0;
for K in 1 .. Number loop
  Sum := Sum + Number / K;
end loop;

I fail to see how this is even connected to shuffling.

^ permalink raw reply	[relevance 0%]

* Re: How to shuffle/jumble letters of a given word?
    2015-06-29 20:21  4% ` Austin Obyrne
@ 2015-06-30 12:29  5% ` Austin Obyrne
  2015-07-01 10:40  0%   ` darkestkhan
  1 sibling, 1 reply; 200+ results
From: Austin Obyrne @ 2015-06-30 12:29 UTC (permalink / raw)


On Sunday, June 28, 2015 at 3:06:29 PM UTC+1, Trish Cayetano wrote:
> I am creating a "text twist game" where you guess the words in a jumbled manner. How do I set the code to shuffle the letters? 
> 
> Example: word to be guessed is HELLO
> 
> What should be displayed is: LOLEH or LELHO
> 
> Thanks in advance!

There are 10 ways of shuffling 'Hello'

In my program source code (posted earlier)the parameters "Step" and "Repeats" may be set as follows'

Step       Repeats
   1                5
   2                2
   3                1
   4                1
   5                1

These have been tested and they all work.
*They may not all be suitable for your purposes on the occasion but they do work technically.

Try them.

The source code I posted earlier will copy 'n paste directly into your AdaGide editor for immediate running.

These results will often need some user-assistance but at least you can see what is available to you for your program.

Also,

Herewith is a program that will calculate the scrambling parameters for you as general options to insert for 'Step' and 'Repeat' in your scrambling program

WITH Ada.Text_IO;
WITH Ada.Integer_Text_IO;
PROCEDURE Find_Scrambling_Parameters IS
-------------------------------------------------------------------------
--| This utility calculates the number of parameters that may be used
--| to scramble a particular number in that many ways.
--| Copyright © 2015 Austin O'Byrne.
--| Last modified April 2015.
-------------------------------------------------------------------------
  SUM    : Integer;
  Number : CONSTANT Integer:= 5; - - Number (Wordlength) for analysing as parameters
  Line_Number: Integer;
  View       : Character;

BEGIN  -- Find_Scrambling_Parameters
    SUM := 0;
    Line_Number:=0;
    Ada.Text_IO.New_Line(2);
    Ada.Text_IO.Put(Item => "                 Step     Times  Parameters space ");
    Ada.Text_IO.New_Line(2);
  FOR I in 1 .. Number LOOP
    Line_Number := Line_Number + 1;
    SUM := SUM + Number / I;
    Ada.Integer_Text_IO.Put(Item => I, Width => 20);
    Ada.Integer_Text_IO.Put(Item => Number/ I, Width => 10);
    Ada.Integer_Text_IO.Put(Item => Sum, Width => 10);
    Ada.Text_IO.New_Line;
    IF Line_Number REM 50 = 0 THEN   --stalls program for viewing
      Ada.Text_IO.Put(Item => "         ");
      Ada.Text_IO.Put(Item => " - press any key/return to continue > ");
      Ada.Text_IO.Get(Item => View);
    END IF;
  END LOOP;

     Ada.Text_IO.Put(Item => " There are ");
     Ada.Integer_Text_IO.Put(Item => Sum, Width => 2);
     Ada.Text_IO.Put(Item => " secret ways of scrambling this string of ciphertext. ");


END Find_Scrambling_Parameters;


(This should copy ' n paste directly into 'AdaGide' also).

Cheers,

Come back if you wish.

Austin


^ permalink raw reply	[relevance 5%]

* Re: How to shuffle/jumble letters of a given word?
  @ 2015-06-29 20:21  4% ` Austin Obyrne
  2015-06-30 12:29  5% ` Austin Obyrne
  1 sibling, 0 replies; 200+ results
From: Austin Obyrne @ 2015-06-29 20:21 UTC (permalink / raw)


On Sunday, June 28, 2015 at 3:06:29 PM UTC+1, Trish Cayetano wrote:
> I am creating a "text twist game" where you guess the words in a jumbled manner. How do I set the code to shuffle the letters? 
> 
> Example: word to be guessed is HELLO
> 
> What should be displayed is: LOLEH or LELHO
> 
> Thanks in advance!

Hi Trish,

This may not be sophisticated enough for what you want but it works.
Try it with the word "Milestone"
Note: You must set the 'wordlength' and the scrambling parameters ('Step' and 'Repeats') to suit - *the product of those must not exceed the 'Wordlength' other wise they will fall off the end of the arrays.

I can do better if you really want to include sentences or groups of letters as words also.

Cheers - Austin

With Ada.Text_IO;
With Ada.Integer_Text_IO;
Procedure Scramble_Letters is
-------------------------------------------------------------------------
--| The program reads in a prescribed word of declared length 
--| from the key board stores the characters and scrambles them.
------------------------------------------------------------------------- 
   X    : Integer;
  Total : Integer;
 
  WordLength: Constant Integer:= 9; -- set the wordlength here
  
  Step    : Constant Integer := 4;
  Repeats : Constant Integer := 2;
  -- Step x Repeats =< WordLength --

  SUBTYPE Index_1 IS Positive RANGE 1 .. 100;
  Type ReadInArray IS ARRAY (Index_1) OF Character;
  NextChar: ReadInArray:= (others => ' ');  -- Stores the plaintext 'NextChar' items being read in.

  SUBTYPE Index_2 IS Positive RANGE 1 .. 100000;
  TYPE UnscrambledNextChars IS ARRAY (Index_2) OF Character;
  Alpha :  UnscrambledNextChars := (others => ' '); -- before scrambling

  SUBTYPE Index_3 IS Positive RANGE 1 .. 100000;
  TYPE ScrambledNextChars_Array IS ARRAY (Index_3) OF Character;
  Beta : ScrambledNextChars_Array := (others => ' '); --after scrambling

          ----------------------------------------------------------

  PROCEDURE Load_n_Scramble_Letters IS
  -- Pre : nil
  -- Post: nil

BEGIN  -- Load_n_Scramble_Letters

  FOR I IN 1 .. Total LOOP
   Alpha(I):= NextChar(I);
   Beta (I):= NextChar(I);
  END LOOP;
  Ada.Text_IO.New_Line(2);
  Ada.Text_IO.Put(Item => "                                Before    After ");--
    X := 0;
  FOR Repeater IN 1 .. Repeats LOOP
  FOR Count IN REVERSE X+1 .. X+Step LOOP
    X:=X+1;
  Beta(X) := Alpha(Count);
  Ada.Text_IO.New_Line(1);  --
  Ada.Text_IO.Put(Item => "                                  ");--
  Ada.Text_IO.Put(Item => Alpha(X));  --
  Ada.Text_IO.Put(Item => "         ");--
  Ada.Text_IO.Put(Item => Beta(X));  --
  END LOOP;
    Ada.Text_IO.New_Line;--
    Ada.Text_IO.Put(item => "                                ---------------");--
  END LOOP;
End Load_n_Scramble_Letters;

              ----------------------------------------------------------------------------

BEGIN  -- Scramble_Letters
    Total:=0;
  FOR I in 1 .. WordLength LOOP
    Total := Total +1;
    Ada.Text_IO.Put(Item => "Enter the character number");
    Ada.Integer_Text_IO.Put(Item => I, Width => 2);
    Ada.Text_IO.Put(Item => " > " );
    Ada.Text_IO.Get(Item => NextChar(Total));
  END LOOP;
    Ada.Text_IO.New_Line;
    Ada.Text_IO.Put(Item => " That's it - the word for scrambling is > ");
  FOR I in 1 .. WordLength LOOP
    Ada.Text_IO.Put(Item => NextChar(I));
  END LOOP;
    Load_n_Scramble_Letters;  -- goes to the scrambling procedure from here
END Scramble_Letters;
            
             ----------------------------------------------------------------

^ permalink raw reply	[relevance 4%]

* Re: Is this a bug in my code or the compiler?
  @ 2015-06-13 16:43  4%     ` Jacob Sparre Andersen
  0 siblings, 0 replies; 200+ results
From: Jacob Sparre Andersen @ 2015-06-13 16:43 UTC (permalink / raw)


"J-P. Rosen" <rosen@adalog.fr> writes:

> Le 13/06/2015 15:33, Jacob Sparre Andersen a écrit :
>>   procedure P (A, B : in out T);
>> 
>>    P (C, C);
>> 
>> But I can't get it to complain about a simplified variation of your
>> case.
>> 
>> Maybe there is an AdaControl rule to detect this kind of problem. 
> Of course. It's called Parameter_Aliasing :-)

I tried it without luck on this test case:

% cat bad_style_2.adb
with Ada.Integer_Text_IO,
     Ada.Text_IO;

procedure Bad_Style_2 is
   function F (I : in out Integer) return Character;
   function G (I : in out Integer) return String;

   function F (I : in out Integer) return Character is
   begin
      return R : Character do
         if I < 0 then
            R := '-';
         else
            R := '+';
         end if;

         I := 2 * I;
      end return;
   end F;

   function G (I : in out Integer) return String is
   begin
      return R : constant String := Integer'Image (I) do
         I := I - 1;
      end return;
   end G;

   C : Integer := 3;
begin
   Ada.Text_IO.Put_Line (F (C) & G (C));
   Ada.Integer_Text_IO.Put (C);
end Bad_Style_2;
% adactl -l 'check parameter_aliasing' bad_style_2.adb
%

I.e. no detection of "expression parameter aliasing" (or what we should
call it).  I think it is only slightly harder to detect than plain
parameter aliasing, but I'm not yet quite proficient enough in ASIS to
promise to contribute a new rule to AdaControl.

Greetings,

Jacob
-- 
"It is very easy to get ridiculously confused about the
 tenses of time travel, but most things can be resolved
 by a sufficiently large ego."

^ permalink raw reply	[relevance 4%]

* Re: Prime sieve
  2015-05-27 14:35  5% Prime sieve montgrimpulo
@ 2015-05-27 17:39  0% ` Jeffrey R. Carter
  0 siblings, 0 replies; 200+ results
From: Jeffrey R. Carter @ 2015-05-27 17:39 UTC (permalink / raw)


On 05/27/2015 07:35 AM, montgrimpulo wrote:
> with Ada.Text_IO;         use Ada.Text_IO;
> with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
> procedure Primes_by_Sieve is
>    task type Sieve is
>       entry Pass_on (Int : Integer);

What happens when someone passes a negative value to Pass_On? If only a certain
range of values is acceptable, it's better to use an appropriate (sub)type to
prevent the use of invalid values.

>    type Sieve_Ptr is access Sieve;

Access types are not needed for this problem. Not using this access type
simplifies the body of Sieve.

>    task body P6n is
>       Limit : constant Integer := 2580976;

This constant does not need to be typed. I always prefer named numbers to typed
constants.

The ARM only guarantees a range of -(2 ** 15) + 1 .. (2 ** 15) - 1 for Integer.
This value makes your program non-portable.

>       while Num <= Limit loop

Why not use a for loop?

-- 
Jeff Carter
"This school was here before you came,
and it'll be here before you go."
Horse Feathers
48

^ permalink raw reply	[relevance 0%]

* Prime sieve
@ 2015-05-27 14:35  5% montgrimpulo
  2015-05-27 17:39  0% ` Jeffrey R. Carter
  0 siblings, 1 reply; 200+ results
From: montgrimpulo @ 2015-05-27 14:35 UTC (permalink / raw)


with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Primes_by_Sieve is
   task type Sieve is
      entry Pass_on (Int : Integer);
   end Sieve;

   task P6n;

   type Sieve_Ptr is access Sieve;

   function Get_New_Sieve return Sieve_Ptr is
   begin
      return new Sieve;
   end Get_New_Sieve;

   task body P6n is
      Limit : constant Integer := 2580976;
      Num   : Integer          := 1;
      S     : Sieve_Ptr        := new Sieve;
   begin
      while Num <= Limit loop
         S.Pass_on (6 * Num - 1);
         S.Pass_on (6 * Num + 1);
         Num := Num + 1;
      end loop;
   end P6n;

   task body Sieve is
      New_Sieve  : Sieve_Ptr;
      Prime, Num : Integer;
   begin
      accept Pass_on (Int : Integer) do
         Prime := Int;
      end Pass_on;
      New_Line;
      Put (Prime);
      loop
         select
            accept Pass_on (Int : Integer) do
               Num := Int;
            end Pass_on;
         or
            terminate;
         end select;
         exit when Num rem Prime /= 0;
      end loop;

      New_Sieve := Get_New_Sieve;
      New_Sieve.Pass_on (Num);

      loop
         select
            accept Pass_on (Int : Integer) do
               Num := Int;
            end Pass_on;
         or
            terminate;
         end select;
         if Num rem Prime /= 0 then
            New_Sieve.Pass_on (Num);
         end if;
      end loop;
   end Sieve;

begin
   null;
end Primes_by_Sieve;

The program above stops normally long before Limit (2580976). Which internal 
restrictions do apply (GNAT, GPS 4.9.1) ?

^ permalink raw reply	[relevance 5%]

* Re: Ada Connections to this Crypto.
  @ 2014-12-20 22:15  4%                     ` MM
  0 siblings, 0 replies; 200+ results
From: MM @ 2014-12-20 22:15 UTC (permalink / raw)


On Saturday, 20 December 2014 18:57:27 UTC+2, Dennis Lee Bieber  wrote:
> 	Ah, only a 6X expansion factor presuming the real values are 16-bit
> integers (they're too large for a byte, but none have gone high enough to
> require more than 16-bits... Based on the visual scan, 13-bit unsigned is
> sufficient). I'll ignore the ~15X expansion for the decimal ASCII he is so
> enamored of...

No, they are regular integers. The reduction in length is cunning choice
of encryption parameters resulting in a desired short output from a regular
ada.integer_text_io.put()n usage.

He's not nearly good enough of a programmer to constrain his output to
GF(2^8) or anything sane like that.

M
-- 

^ permalink raw reply	[relevance 4%]

* Re: The enormous potential that programming LaTeX in Ada presents.
  @ 2014-12-03 22:39  4%       ` mrvmurray
  0 siblings, 0 replies; 200+ results
From: mrvmurray @ 2014-12-03 22:39 UTC (permalink / raw)


On Wednesday, 3 December 2014 20:57:02 UTC, Pascal Obry  wrote:
> So what do you mean by the above?

It is a long-standing misconception of his. In 10+ years he's been
unable to break away from the idea that plainTEXT can be anything
input to a cipher, and he's convinced that encryption is limited to
human-readable text. He has many similar misconceptions about
computers in general.

This is not helped by the fact that he only knows how to use the
ada.text_io and ada.integer_text_io packages, and has proven
himself aggressively hostile to attempting to use something more
suitable. He is similarly hostile to bug reports in his code.

Thus, his cipher will only encrypt (badly, mind you) bytes in the
numeric range 32..126. Newlines are passed through unchanged
and other bytes cause his program to crash.

M


^ permalink raw reply	[relevance 4%]

* Re: Help with an errant 'IF' statement please.
  2014-12-01 22:20  6%               ` Stephen Leake
@ 2014-12-02  2:57  0%                 ` Austin Obyrne
  0 siblings, 0 replies; 200+ results
From: Austin Obyrne @ 2014-12-02  2:57 UTC (permalink / raw)


On Monday, December 1, 2014 10:20:52 PM UTC, Stephen Leake wrote:
> Austin Obyrne <austin.obyrne@hotmail.com> writes:
> 
> >>   Time_Ex_1;
> >>   Count  := Phi;    --initialising change-of-origin Count
> 
> <snip>
> 
> In order to help you understand what you need to change in this post so
> we can help, I've attempted to make this compile. Here's a modified
> version, with some fixes, and some FIXME: comments:
> 
> with Ada.Text_IO;
> procedure Obyrne_1
> is
>    --  FIXME: put all required definitions here, as reported by the
>    --  compilation errors: Time_Ex_1, Count, Phi, Resets, Total, n,
>    --  Number, NextChar, Line_Number, Sentinel, Span, Counter, Image,
>    --  Compose_CipherText_Items, Q, I_Num, Time_Ex_2
>    --
>    --  While you are doing that, delete any that are not needed to
>    --  show the problem.
> begin
> 
>    Time_Ex_1;
>    Count  := Phi;    --initialising change-of-origin Count
>    Resets := 0;
>    Total  := 0;
>    NextChar := ' ';    --initialising to pre-empt error message
>    Line_Number:= 0;
>    LOOP
>       EXIT WHEN NextChar = Sentinel;
>       Count:= Count+1;               -- change-of-origin count reinitialising
>       IF Count REM (Span + Phi +1) = 0 THEN -- Reset signal
>          Count:= 1;
>          Resets:= Resets +1;
>       END IF;
>       Total := Total +1;
>       Ada.Text_IO.Get(Item => NextChar);
>       Counter := Counter +1;
>       Total := Total +1;
>       Image(Counter):= NextChar;
>       --  FIXME: do _not_ include commented out code, unless it is part of the explanation of the problem
> 
>       --  FIXME: most of this output is _not_ essential to show the bug; delete them.
>       Ada.Text_IO.New_Line;
>       Ada.Text_IO.Put(Item => "         ");
>       Ada.Text_IO.Put(Item => NextChar);
>       Ada.Text_IO.Put(Item => "                - Current PlainText for encryption");
>       Ada.Text_IO.New_Line;
>       Ada.Text_IO.Put(Item => "        ");
>       Ada.Text_IO.Put(Item => " Phi ");
>       Ada.Text_IO.Put(Item => "             - ");
>       Ada.Integer_Text_IO.Put(Item => Phi, Width => 2);
>       Ada.Text_IO.New_Line;
>       Ada.Text_IO.Put(Item => "        ");
>       Ada.Text_IO.Put(Item => " Count ");
>       Ada.Text_IO.Put(Item => "           - ");
>       Ada.Integer_Text_IO.Put(Item => Count, Width => 2);
>       Ada.Text_IO.New_Line;
>       Ada.Text_IO.Put(Item => "        ");
>       Ada.Text_IO.Put(Item => " Total ");
>       Ada.Text_IO.Put(Item => "           - ");
>       Ada.Integer_Text_IO.Put(Item => Total, Width => 2);
>       Ada.Text_IO.New_line;
>       Ada.Integer_Text_IO.Put(Item => Character'Pos(Nextchar), Width => 11);
>       Ada.Text_IO.Put
>         (Item => "               - Value in ASCII of current plaintext");
>       Ada.Text_IO.New_line;
>       Compute_Normal;
>       Ada.Integer_Text_IO.Put(Item => Normal(1), Width => 4);
>       Ada.Integer_Text_IO.Put(Item => Normal(2), Width => 8);
>       Ada.Integer_Text_IO.Put(Item => Normal(3), Width => 8);
>       Ada.Text_IO.Put(Item => "      - Normal vector -  fixed in this cipher");
>       Ada.Text_IO.New_Line;
>       Ada.Integer_Text_IO.Put(Item => S_1, Width => 4);
>       Ada.Integer_Text_IO.Put(Item => S_2, Width => 8);
>       Ada.Integer_Text_IO.Put(Item => S_3, Width => 8);
>       Ada.Text_IO.Put
>         (Item => "      - VeeZero - fixed in this cipher");
>       Ada.Text_IO.New_Line;
>       Ada.Integer_Text_IO.Put(Item => T_1, Width => 4);
>       Ada.Integer_Text_IO.Put(Item => T_2, Width => 8);
>       Ada.Integer_Text_IO.Put(Item => T_3, Width => 8);
>       Ada.Text_IO.Put
>         (Item => "      - VeeOne - fixed in this cipher.");
>       Ada.Text_IO.New_Line;
>       Compute_Normal;
>       Ada.Integer_Text_IO.Put(Item => Normal(1), Width => 4);
>       Ada.Integer_Text_IO.Put(Item => Normal(2), Width => 8);
>       Ada.Integer_Text_IO.Put(Item => Normal(3), Width => 8);
>       Ada.Text_IO.Put(Item => "      - Normal vector -  fixed in this cipher");
>       Ada.Text_IO.New_Line;
>       n :=(Character'Pos(NextChar));
>       Ada.Integer_Text_IO.Put(Item => n, Width =>12);
>       Ada.Text_IO.Put
>         (Item => "              - face value 'n' of current plaintext in ASCII");
>       Ada.Text_IO.New_Line;
>       n := Number(Character'Pos(NextChar));  -- renumbered by Alice
>       Ada.Integer_Text_IO.Put(Item => n, Width =>12);
>       Ada.Text_IO.Put
>         (Item => "              - rendered value of 'n'in the encryption alphabet");
>       Compute_Position_Vector(Number => n);
>       Ada.Text_IO.New_Line;
>       Ada.Integer_Text_IO.Put(Item => Pn(1), Width => 8);
>       Ada.Integer_Text_IO.Put(Item => Pn(2), Width => 8);
>       Ada.Integer_Text_IO.Put(Item => Pn(3), Width => 8);
>       Ada.Text_IO.Put(Item => "  - Position vector ('Pn') for this 'n'. ");
>       Ada.Text_IO.New_Line;
>       Ada.Integer_Text_IO.Put(Item => Hash_2(Count), Width => 8);
>       Ada.Integer_Text_IO.Put(Item => Hash_11(Count), Width => 8);
>       Ada.Integer_Text_IO.Put(Item => Hash_12(Count), Width => 8);
>       Ada.Text_IO.Put
>         (Item => "  - Change-of-origin vector to be given to this Pn item");
>       Ada.Text_IO.New_Line;
>       FOR I IN 1 .. 3 LOOP
>          W(I):= Compose_CipherText_Items( Numin => I);
>          Ada.Integer_Text_IO.Put(File => OutData, Item =>  W(I));
>       END LOOP;
>       Ada.Integer_Text_IO.Put( Item =>  W(1), Width => 9);
>       Ada.Integer_Text_IO.Put( Item =>  W(2), Width => 8);
>       Ada.Integer_Text_IO.Put( Item =>  W(3), Width => 8);
>       Ada.Text_IO.Put(Item =>" - Ciphertext for this item of plaintext");
>       Q:= W(1)REM 1000000;
>       I_Num(Q) := I_Num(Q)+1;
>       --  Q:= W(2)REM 1000000;
>       --  I_Num(Q) := I_Num(Q)+1;
>       --  Q:= W(3)REM 1000000;
>       --  I_Num(Q) := I_Num(Q)+1;
>       --  Ada.Text_IO.New_Line;
>       --  Ada.Integer_Text_IO.Put(Item => AllTold, Width =>4);
>       --  Ada.Integer_Text_IO.Put(Item => Total, Width =>8);
>       --  Ada.Integer_Text_IO.Put(Item => InToto, Width =>8);
>       --  Ada.Text_IO.Put(Item => "      - Compares 'AllTold','Total','InToto' integrators'");
>       Line_Number:= Line_Number+1;
>       Ada.Text_IO.New_Line(1);
>       Ada.Text_IO.Put(Item => "                          - Character number ");
>       Ada.Integer_Text_IO.Put(Item => Line_Number, Width => 1);
>       Ada.Text_IO.New_Line(1);
>       IF Line_Number REM 12 = 0 THEN
>          Ada.Text_IO.New_Line(1);
>          Ada.Text_IO.Put(Item => "                       ");
>          Ada.Text_IO.Put(Item => " # - press any key/return to continue > ");
>          Ada.Text_IO.Get(Item => View);
>       END IF;
>       Ada.Text_IO.New_Line;
>       Ada.Text_IO.Put(Item => "  ---------------------------------------------------------------------------");
>    END LOOP;
>    Ada.Text_IO.Close(File => Outdata);
>    Time_Ex_2;  -- time at end
> end Obyrne_1;
> 
> This gives the following compilation errors:
> 
> obyrne_1.adb:6:04: "Time_Ex_1" is undefined
> obyrne_1.adb:7:04: "Count" is undefined (more references follow)
> obyrne_1.adb:7:14: "Phi" is undefined (more references follow)
> obyrne_1.adb:8:04: "Resets" is undefined (more references follow)
> obyrne_1.adb:9:04: "Total" is undefined (more references follow)
> obyrne_1.adb:10:04: "NextChar" is undefined (more references follow)
> obyrne_1.adb:11:04: "Line_Number" is undefined (more references follow)
> obyrne_1.adb:13:28: "Sentinel" is undefined
> obyrne_1.adb:15:21: "Span" is undefined
> obyrne_1.adb:20:07: "Ada" is undefined (more references follow)
> obyrne_1.adb:20:07: missing "with Ada.Text_IO;"
> obyrne_1.adb:21:18: "Counter" is undefined (more references follow)
> obyrne_1.adb:23:07: "Image" is undefined
> obyrne_1.adb:51:07: "Compute_Normal" is undefined (more references follow)
> obyrne_1.adb:75:07: "n" is undefined (more references follow)
> obyrne_1.adb:80:12: "Number" is undefined
> obyrne_1.adb:84:07: "Compute_Position_Vector" is undefined
> obyrne_1.adb:98:10: "W" is undefined (more references follow)
> obyrne_1.adb:98:17: "Compose_CipherText_Items" is undefined
> obyrne_1.adb:105:07: "Q" is undefined (more references follow)
> obyrne_1.adb:106:19: "I_Num" is undefined (more references follow)
> obyrne_1.adb:131:04: "Time_Ex_2" is undefined
> 
> Until these errors are fixed, we can't help you, because we can't tell
> where the problem is.
> 
> See the FIXME: comments for more detailed advice on how to change the
> code.
> 
> Your first post said there was an "if" statement that did not work, so
> the code you present should contain just that "if" statment, together
> with the required declarations, and some Text_IO.Put_lines to
> demonstrate the problem.
> 
> In addition, please state clearly what the problem is. The only thing
> you've said so far is "it doesn't work". That usually means "it doesn't
> do what I want it to do". Since we don't know what you want it to do, we
> can't help.
> 
> You could say something like:
> 
>     I expect line 23 to output "23", but it outputs "42".
> 
> -- 
> -- Stephe

Hi Stephe,

I am overwhelmed with the volume of help from everybody. With hindsight I should have taken more care in presenting my problem. Now that I know the drill I will be more careful in the future.  Part of my problem is in not learning Ada properly. I go for problem solving by alternative methods instead of fine tuning the method in hand.

In passing, I note that professor M.B. Feldman is posting here also today.  I cannot overstate the email help this man gave me in getting stared with Ada-95 - thanks again Professor - your book was and is excellent (if you can get a used copy).

adacrypt.


^ permalink raw reply	[relevance 0%]

* Re: Help with an errant 'IF' statement please.
  2014-11-30 13:01  0%             ` Austin Obyrne
@ 2014-12-01 22:20  6%               ` Stephen Leake
  2014-12-02  2:57  0%                 ` Austin Obyrne
  0 siblings, 1 reply; 200+ results
From: Stephen Leake @ 2014-12-01 22:20 UTC (permalink / raw)


Austin Obyrne <austin.obyrne@hotmail.com> writes:

>>   Time_Ex_1;
>>   Count  := Phi;    --initialising change-of-origin Count

<snip>

In order to help you understand what you need to change in this post so
we can help, I've attempted to make this compile. Here's a modified
version, with some fixes, and some FIXME: comments:

with Ada.Text_IO;
procedure Obyrne_1
is
   --  FIXME: put all required definitions here, as reported by the
   --  compilation errors: Time_Ex_1, Count, Phi, Resets, Total, n,
   --  Number, NextChar, Line_Number, Sentinel, Span, Counter, Image,
   --  Compose_CipherText_Items, Q, I_Num, Time_Ex_2
   --
   --  While you are doing that, delete any that are not needed to
   --  show the problem.
begin

   Time_Ex_1;
   Count  := Phi;    --initialising change-of-origin Count
   Resets := 0;
   Total  := 0;
   NextChar := ' ';    --initialising to pre-empt error message
   Line_Number:= 0;
   LOOP
      EXIT WHEN NextChar = Sentinel;
      Count:= Count+1;               -- change-of-origin count reinitialising
      IF Count REM (Span + Phi +1) = 0 THEN -- Reset signal
         Count:= 1;
         Resets:= Resets +1;
      END IF;
      Total := Total +1;
      Ada.Text_IO.Get(Item => NextChar);
      Counter := Counter +1;
      Total := Total +1;
      Image(Counter):= NextChar;
      --  FIXME: do _not_ include commented out code, unless it is part of the explanation of the problem

      --  FIXME: most of this output is _not_ essential to show the bug; delete them.
      Ada.Text_IO.New_Line;
      Ada.Text_IO.Put(Item => "         ");
      Ada.Text_IO.Put(Item => NextChar);
      Ada.Text_IO.Put(Item => "                - Current PlainText for encryption");
      Ada.Text_IO.New_Line;
      Ada.Text_IO.Put(Item => "        ");
      Ada.Text_IO.Put(Item => " Phi ");
      Ada.Text_IO.Put(Item => "             - ");
      Ada.Integer_Text_IO.Put(Item => Phi, Width => 2);
      Ada.Text_IO.New_Line;
      Ada.Text_IO.Put(Item => "        ");
      Ada.Text_IO.Put(Item => " Count ");
      Ada.Text_IO.Put(Item => "           - ");
      Ada.Integer_Text_IO.Put(Item => Count, Width => 2);
      Ada.Text_IO.New_Line;
      Ada.Text_IO.Put(Item => "        ");
      Ada.Text_IO.Put(Item => " Total ");
      Ada.Text_IO.Put(Item => "           - ");
      Ada.Integer_Text_IO.Put(Item => Total, Width => 2);
      Ada.Text_IO.New_line;
      Ada.Integer_Text_IO.Put(Item => Character'Pos(Nextchar), Width => 11);
      Ada.Text_IO.Put
        (Item => "               - Value in ASCII of current plaintext");
      Ada.Text_IO.New_line;
      Compute_Normal;
      Ada.Integer_Text_IO.Put(Item => Normal(1), Width => 4);
      Ada.Integer_Text_IO.Put(Item => Normal(2), Width => 8);
      Ada.Integer_Text_IO.Put(Item => Normal(3), Width => 8);
      Ada.Text_IO.Put(Item => "      - Normal vector -  fixed in this cipher");
      Ada.Text_IO.New_Line;
      Ada.Integer_Text_IO.Put(Item => S_1, Width => 4);
      Ada.Integer_Text_IO.Put(Item => S_2, Width => 8);
      Ada.Integer_Text_IO.Put(Item => S_3, Width => 8);
      Ada.Text_IO.Put
        (Item => "      - VeeZero - fixed in this cipher");
      Ada.Text_IO.New_Line;
      Ada.Integer_Text_IO.Put(Item => T_1, Width => 4);
      Ada.Integer_Text_IO.Put(Item => T_2, Width => 8);
      Ada.Integer_Text_IO.Put(Item => T_3, Width => 8);
      Ada.Text_IO.Put
        (Item => "      - VeeOne - fixed in this cipher.");
      Ada.Text_IO.New_Line;
      Compute_Normal;
      Ada.Integer_Text_IO.Put(Item => Normal(1), Width => 4);
      Ada.Integer_Text_IO.Put(Item => Normal(2), Width => 8);
      Ada.Integer_Text_IO.Put(Item => Normal(3), Width => 8);
      Ada.Text_IO.Put(Item => "      - Normal vector -  fixed in this cipher");
      Ada.Text_IO.New_Line;
      n :=(Character'Pos(NextChar));
      Ada.Integer_Text_IO.Put(Item => n, Width =>12);
      Ada.Text_IO.Put
        (Item => "              - face value 'n' of current plaintext in ASCII");
      Ada.Text_IO.New_Line;
      n := Number(Character'Pos(NextChar));  -- renumbered by Alice
      Ada.Integer_Text_IO.Put(Item => n, Width =>12);
      Ada.Text_IO.Put
        (Item => "              - rendered value of 'n'in the encryption alphabet");
      Compute_Position_Vector(Number => n);
      Ada.Text_IO.New_Line;
      Ada.Integer_Text_IO.Put(Item => Pn(1), Width => 8);
      Ada.Integer_Text_IO.Put(Item => Pn(2), Width => 8);
      Ada.Integer_Text_IO.Put(Item => Pn(3), Width => 8);
      Ada.Text_IO.Put(Item => "  - Position vector ('Pn') for this 'n'. ");
      Ada.Text_IO.New_Line;
      Ada.Integer_Text_IO.Put(Item => Hash_2(Count), Width => 8);
      Ada.Integer_Text_IO.Put(Item => Hash_11(Count), Width => 8);
      Ada.Integer_Text_IO.Put(Item => Hash_12(Count), Width => 8);
      Ada.Text_IO.Put
        (Item => "  - Change-of-origin vector to be given to this Pn item");
      Ada.Text_IO.New_Line;
      FOR I IN 1 .. 3 LOOP
         W(I):= Compose_CipherText_Items( Numin => I);
         Ada.Integer_Text_IO.Put(File => OutData, Item =>  W(I));
      END LOOP;
      Ada.Integer_Text_IO.Put( Item =>  W(1), Width => 9);
      Ada.Integer_Text_IO.Put( Item =>  W(2), Width => 8);
      Ada.Integer_Text_IO.Put( Item =>  W(3), Width => 8);
      Ada.Text_IO.Put(Item =>" - Ciphertext for this item of plaintext");
      Q:= W(1)REM 1000000;
      I_Num(Q) := I_Num(Q)+1;
      --  Q:= W(2)REM 1000000;
      --  I_Num(Q) := I_Num(Q)+1;
      --  Q:= W(3)REM 1000000;
      --  I_Num(Q) := I_Num(Q)+1;
      --  Ada.Text_IO.New_Line;
      --  Ada.Integer_Text_IO.Put(Item => AllTold, Width =>4);
      --  Ada.Integer_Text_IO.Put(Item => Total, Width =>8);
      --  Ada.Integer_Text_IO.Put(Item => InToto, Width =>8);
      --  Ada.Text_IO.Put(Item => "      - Compares 'AllTold','Total','InToto' integrators'");
      Line_Number:= Line_Number+1;
      Ada.Text_IO.New_Line(1);
      Ada.Text_IO.Put(Item => "                          - Character number ");
      Ada.Integer_Text_IO.Put(Item => Line_Number, Width => 1);
      Ada.Text_IO.New_Line(1);
      IF Line_Number REM 12 = 0 THEN
         Ada.Text_IO.New_Line(1);
         Ada.Text_IO.Put(Item => "                       ");
         Ada.Text_IO.Put(Item => " # - press any key/return to continue > ");
         Ada.Text_IO.Get(Item => View);
      END IF;
      Ada.Text_IO.New_Line;
      Ada.Text_IO.Put(Item => "  ---------------------------------------------------------------------------");
   END LOOP;
   Ada.Text_IO.Close(File => Outdata);
   Time_Ex_2;  -- time at end
end Obyrne_1;

This gives the following compilation errors:

obyrne_1.adb:6:04: "Time_Ex_1" is undefined
obyrne_1.adb:7:04: "Count" is undefined (more references follow)
obyrne_1.adb:7:14: "Phi" is undefined (more references follow)
obyrne_1.adb:8:04: "Resets" is undefined (more references follow)
obyrne_1.adb:9:04: "Total" is undefined (more references follow)
obyrne_1.adb:10:04: "NextChar" is undefined (more references follow)
obyrne_1.adb:11:04: "Line_Number" is undefined (more references follow)
obyrne_1.adb:13:28: "Sentinel" is undefined
obyrne_1.adb:15:21: "Span" is undefined
obyrne_1.adb:20:07: "Ada" is undefined (more references follow)
obyrne_1.adb:20:07: missing "with Ada.Text_IO;"
obyrne_1.adb:21:18: "Counter" is undefined (more references follow)
obyrne_1.adb:23:07: "Image" is undefined
obyrne_1.adb:51:07: "Compute_Normal" is undefined (more references follow)
obyrne_1.adb:75:07: "n" is undefined (more references follow)
obyrne_1.adb:80:12: "Number" is undefined
obyrne_1.adb:84:07: "Compute_Position_Vector" is undefined
obyrne_1.adb:98:10: "W" is undefined (more references follow)
obyrne_1.adb:98:17: "Compose_CipherText_Items" is undefined
obyrne_1.adb:105:07: "Q" is undefined (more references follow)
obyrne_1.adb:106:19: "I_Num" is undefined (more references follow)
obyrne_1.adb:131:04: "Time_Ex_2" is undefined

Until these errors are fixed, we can't help you, because we can't tell
where the problem is.

See the FIXME: comments for more detailed advice on how to change the
code.

Your first post said there was an "if" statement that did not work, so
the code you present should contain just that "if" statment, together
with the required declarations, and some Text_IO.Put_lines to
demonstrate the problem.

In addition, please state clearly what the problem is. The only thing
you've said so far is "it doesn't work". That usually means "it doesn't
do what I want it to do". Since we don't know what you want it to do, we
can't help.

You could say something like:

    I expect line 23 to output "23", but it outputs "42".

-- 
-- Stephe


^ permalink raw reply	[relevance 6%]

* Re: Help with an errant 'IF' statement please.
  2014-11-30 12:58  7%           ` Austin Obyrne
@ 2014-11-30 13:01  0%             ` Austin Obyrne
  2014-12-01 22:20  6%               ` Stephen Leake
  0 siblings, 1 reply; 200+ results
From: Austin Obyrne @ 2014-11-30 13:01 UTC (permalink / raw)


On Sunday, November 30, 2014 12:58:34 PM UTC, Austin Obyrne wrote:
> On Sunday, November 30, 2014 11:18:33 AM UTC, Simon Clubley wrote:
> > On 2014-11-30, Austin Obyrne <austin.obyrne@hotmail.com> wrote:
> > > On Saturday, November 29, 2014 4:53:48 PM UTC, Dennis Lee Bieber wrote:
> > >> On Sat, 29 Nov 2014 07:05:09 -0800 (PST), Austin Obyrne
> > >> <austin.obyrne@hotmail.com> declaimed the following:
> > >> 
> > >> 
> > >> >LOOP
> > >> >  EXIT WHEN NextChar = Sentinel;
> > >> >
> > >> 	What is the definition of "NextChar", since I don't see it changing
> > >> inside this loop...
> > >>  
> > >
> > > This is the relevant source code at the very start of the program in
> > > question,
> > >
> > >   Total := Total+1;
> > >   Ada.Text_IO.Get(Item => NextChar);
> > >   Image(Total):= NextChar;
> > >  
> > > 'NextChar' is the variable name given to each character being read
> > > in from the keyboard.
> > >
> > 
> > [snip]
> > 
> > > Sorry for taking so long in coming back and thanks for your help - Austin.
> > 
> > Do what I told you to do and write a stripped down standalone test program
> > around the fragment you posted.
> > 
> > You will then see what Dennis (and myself) are telling you.
> > 
> > I could tell you what the problem is, but I think it's more important for
> > you to understand how to find this yourself.
> > 
> > Simon.
> > 
> > -- 
> > Simon Clubley, clubley@remove_me.eisner.decus.org-Earth.UFP
> > Microsoft: Bringing you 1980s technology to a 21st century world
> 
> Hi Simon - herewith the program sourcecode of the procedure in question - I would like to know for future - my main preoccupation is with problem solving but the elegance and efficacy of Ada are important to me also - bear with me -this a an experimental program by me and is not a fine example of programming in Ada. I would appreciate your help - I am going flat out with research work in cryptoland - Ada is a tool to me at the moment until I get more time to 'smell the flowers' of the language proper.
> 
>   Time_Ex_1;
>   Count  := Phi;    --initialising change-of-origin Count
>   Resets := 0;
>   Total  := 0;
>   NextChar := ' ';    --initialising to pre-empt error message
>   Line_Number:= 0;
>   LOOP
>   EXIT WHEN NextChar = Sentinel;
>   Count:= Count+1;               -- change-of-origin count reinitialising
>   IF Count REM (Span + Phi +1) = 0 THEN -- Reset signal
>      Count:= 1;
>      Resets:= Resets +1;
>   END IF;
>   Total := Total +1;
>   Ada.Text_IO.Get(Item => NextChar);
>   Counter := Counter +1;
>   Total := Total +1;
>   Image(Counter):= NextChar;
> --  R := Character 'POS(NextChar);
> --  PlainTextNum(R) := PlainTextNum(R) +1;
>   Ada.Text_IO.New_Line;
>   Ada.Text_IO.Put(Item => "         ");
>   Ada.Text_IO.Put(Item => NextChar);
>   Ada.Text_IO.Put(Item => "                - Current PlainText for encryption");
>   Ada.Text_IO.New_Line;
>   Ada.Text_IO.Put(Item => "        ");
>   Ada.Text_IO.Put(Item => " Phi ");
>   Ada.Text_IO.Put(Item => "             - ");
>   Ada.Integer_Text_IO.Put(Item => Phi, Width => 2);
>   Ada.Text_IO.New_Line;
>   Ada.Text_IO.Put(Item => "        ");
>   Ada.Text_IO.Put(Item => " Count ");
>   Ada.Text_IO.Put(Item => "           - ");
>   Ada.Integer_Text_IO.Put(Item => Count, Width => 2);
>   Ada.Text_IO.New_Line;
>   Ada.Text_IO.Put(Item => "        ");
>   Ada.Text_IO.Put(Item => " Total ");
>   Ada.Text_IO.Put(Item => "           - ");
>   Ada.Integer_Text_IO.Put(Item => Total, Width => 2);
>   Ada.Text_IO.New_line;
>   Ada.Integer_Text_IO.Put(Item => Character'Pos(Nextchar), Width => 11);
>   Ada.Text_IO.Put
>   (Item => "               - Value in ASCII of current plaintext");
>   Ada.Text_IO.New_line;
>   Compute_Normal;
>   Ada.Integer_Text_IO.Put(Item => Normal(1), Width => 4);
>   Ada.Integer_Text_IO.Put(Item => Normal(2), Width => 8);
>   Ada.Integer_Text_IO.Put(Item => Normal(3), Width => 8);
>   Ada.Text_IO.Put(Item => "      - Normal vector -  fixed in this cipher");
>   Ada.Text_IO.New_Line;
>   Ada.Integer_Text_IO.Put(Item => S_1, Width => 4);
>   Ada.Integer_Text_IO.Put(Item => S_2, Width => 8);
>   Ada.Integer_Text_IO.Put(Item => S_3, Width => 8);
>   Ada.Text_IO.Put
>   (Item => "      - VeeZero - fixed in this cipher");
>   Ada.Text_IO.New_Line;
>   Ada.Integer_Text_IO.Put(Item => T_1, Width => 4);
>   Ada.Integer_Text_IO.Put(Item => T_2, Width => 8);
>   Ada.Integer_Text_IO.Put(Item => T_3, Width => 8);
>   Ada.Text_IO.Put
>   (Item => "      - VeeOne - fixed in this cipher.");
>   Ada.Text_IO.New_Line;
>   Compute_Normal;
>   Ada.Integer_Text_IO.Put(Item => Normal(1), Width => 4);
>   Ada.Integer_Text_IO.Put(Item => Normal(2), Width => 8);
>   Ada.Integer_Text_IO.Put(Item => Normal(3), Width => 8);
>   Ada.Text_IO.Put(Item => "      - Normal vector -  fixed in this cipher");
>   Ada.Text_IO.New_Line;
>   n :=(Character'Pos(NextChar));
>   Ada.Integer_Text_IO.Put(Item => n, Width =>12);
>   Ada.Text_IO.Put
>   (Item => "              - face value 'n' of current plaintext in ASCII");
>   Ada.Text_IO.New_Line;
>   n := Number(Character'Pos(NextChar));  -- renumbered by Alice
>   Ada.Integer_Text_IO.Put(Item => n, Width =>12);
>   Ada.Text_IO.Put
>   (Item => "              - rendered value of 'n'in the encryption alphabet");
>   Compute_Position_Vector(Number => n);
>   Ada.Text_IO.New_Line;
>   Ada.Integer_Text_IO.Put(Item => Pn(1), Width => 8);
>   Ada.Integer_Text_IO.Put(Item => Pn(2), Width => 8);
>   Ada.Integer_Text_IO.Put(Item => Pn(3), Width => 8);
>   Ada.Text_IO.Put(Item => "  - Position vector ('Pn') for this 'n'. ");
>   Ada.Text_IO.New_Line;
>   Ada.Integer_Text_IO.Put(Item => Hash_2(Count), Width => 8);
>   Ada.Integer_Text_IO.Put(Item => Hash_11(Count), Width => 8);
>   Ada.Integer_Text_IO.Put(Item => Hash_12(Count), Width => 8);
>   Ada.Text_IO.Put
>   (Item => "  - Change-of-origin vector to be given to this Pn item");
>   Ada.Text_IO.New_Line;
>     FOR I IN 1 .. 3 LOOP
>       W(I):= Compose_CipherText_Items( Numin => I);
>       Ada.Integer_Text_IO.Put(File => OutData, Item =>  W(I));
>     END LOOP;
>   Ada.Integer_Text_IO.Put( Item =>  W(1), Width => 9);
>   Ada.Integer_Text_IO.Put( Item =>  W(2), Width => 8);
>   Ada.Integer_Text_IO.Put( Item =>  W(3), Width => 8);
>   Ada.Text_IO.Put(Item =>" - Ciphertext for this item of plaintext");
>   Q:= W(1)REM 1000000;
>   I_Num(Q) := I_Num(Q)+1;
> --  Q:= W(2)REM 1000000;
> --  I_Num(Q) := I_Num(Q)+1;
> --  Q:= W(3)REM 1000000;
> --  I_Num(Q) := I_Num(Q)+1;
> --  Ada.Text_IO.New_Line;
> --  Ada.Integer_Text_IO.Put(Item => AllTold, Width =>4);
> --  Ada.Integer_Text_IO.Put(Item => Total, Width =>8);
> --  Ada.Integer_Text_IO.Put(Item => InToto, Width =>8);
> --  Ada.Text_IO.Put(Item => "      - Compares 'AllTold','Total','InToto' integrators'");
>   Line_Number:= Line_Number+1;
>   Ada.Text_IO.New_Line(1);
>   Ada.Text_IO.Put(Item => "                          - Character number ");
>   Ada.Integer_Text_IO.Put(Item => Line_Number, Width => 1);
>   Ada.Text_IO.New_Line(1);
>     IF Line_Number REM 12 = 0 THEN
>       Ada.Text_IO.New_Line(1);
>       Ada.Text_IO.Put(Item => "                       ");
>       Ada.Text_IO.Put(Item => " # - press any key/return to continue > ");
>       Ada.Text_IO.Get(Item => View);
>     END IF;
> --    IF W(2)REM 1000000 = 514681 THEN --repeated number in ciphertext say
> --      Ada.Integer_Text_IO.Put (item => W(2) , Width => 20);
> --      Ada.Text_IO.Get(Item => View);
> --    END IF;
>   Ada.Text_IO.New_Line;
>   Ada.Text_IO.Put(Item => "  ---------------------------------------------------------------------------");
>   END LOOP;
>   Ada.Text_IO.Close(File => Outdata);
>   Time_Ex_2;  -- time at end

Their is some experimental debris in there also I'm afraid - apologies for that.


^ permalink raw reply	[relevance 0%]

* Re: Help with an errant 'IF' statement please.
  @ 2014-11-30 12:58  7%           ` Austin Obyrne
  2014-11-30 13:01  0%             ` Austin Obyrne
  0 siblings, 1 reply; 200+ results
From: Austin Obyrne @ 2014-11-30 12:58 UTC (permalink / raw)


On Sunday, November 30, 2014 11:18:33 AM UTC, Simon Clubley wrote:
> On 2014-11-30, Austin Obyrne <austin.obyrne@hotmail.com> wrote:
> > On Saturday, November 29, 2014 4:53:48 PM UTC, Dennis Lee Bieber wrote:
> >> On Sat, 29 Nov 2014 07:05:09 -0800 (PST), Austin Obyrne
> >> <austin.obyrne@hotmail.com> declaimed the following:
> >> 
> >> 
> >> >LOOP
> >> >  EXIT WHEN NextChar = Sentinel;
> >> >
> >> 	What is the definition of "NextChar", since I don't see it changing
> >> inside this loop...
> >>  
> >
> > This is the relevant source code at the very start of the program in
> > question,
> >
> >   Total := Total+1;
> >   Ada.Text_IO.Get(Item => NextChar);
> >   Image(Total):= NextChar;
> >  
> > 'NextChar' is the variable name given to each character being read
> > in from the keyboard.
> >
> 
> [snip]
> 
> > Sorry for taking so long in coming back and thanks for your help - Austin.
> 
> Do what I told you to do and write a stripped down standalone test program
> around the fragment you posted.
> 
> You will then see what Dennis (and myself) are telling you.
> 
> I could tell you what the problem is, but I think it's more important for
> you to understand how to find this yourself.
> 
> Simon.
> 
> -- 
> Simon Clubley, clubley@remove_me.eisner.decus.org-Earth.UFP
> Microsoft: Bringing you 1980s technology to a 21st century world

Hi Simon - herewith the program sourcecode of the procedure in question - I would like to know for future - my main preoccupation is with problem solving but the elegance and efficacy of Ada are important to me also - bear with me -this a an experimental program by me and is not a fine example of programming in Ada. I would appreciate your help - I am going flat out with research work in cryptoland - Ada is a tool to me at the moment until I get more time to 'smell the flowers' of the language proper.

  Time_Ex_1;
  Count  := Phi;    --initialising change-of-origin Count
  Resets := 0;
  Total  := 0;
  NextChar := ' ';    --initialising to pre-empt error message
  Line_Number:= 0;
  LOOP
  EXIT WHEN NextChar = Sentinel;
  Count:= Count+1;               -- change-of-origin count reinitialising
  IF Count REM (Span + Phi +1) = 0 THEN -- Reset signal
     Count:= 1;
     Resets:= Resets +1;
  END IF;
  Total := Total +1;
  Ada.Text_IO.Get(Item => NextChar);
  Counter := Counter +1;
  Total := Total +1;
  Image(Counter):= NextChar;
--  R := Character 'POS(NextChar);
--  PlainTextNum(R) := PlainTextNum(R) +1;
  Ada.Text_IO.New_Line;
  Ada.Text_IO.Put(Item => "         ");
  Ada.Text_IO.Put(Item => NextChar);
  Ada.Text_IO.Put(Item => "                - Current PlainText for encryption");
  Ada.Text_IO.New_Line;
  Ada.Text_IO.Put(Item => "        ");
  Ada.Text_IO.Put(Item => " Phi ");
  Ada.Text_IO.Put(Item => "             - ");
  Ada.Integer_Text_IO.Put(Item => Phi, Width => 2);
  Ada.Text_IO.New_Line;
  Ada.Text_IO.Put(Item => "        ");
  Ada.Text_IO.Put(Item => " Count ");
  Ada.Text_IO.Put(Item => "           - ");
  Ada.Integer_Text_IO.Put(Item => Count, Width => 2);
  Ada.Text_IO.New_Line;
  Ada.Text_IO.Put(Item => "        ");
  Ada.Text_IO.Put(Item => " Total ");
  Ada.Text_IO.Put(Item => "           - ");
  Ada.Integer_Text_IO.Put(Item => Total, Width => 2);
  Ada.Text_IO.New_line;
  Ada.Integer_Text_IO.Put(Item => Character'Pos(Nextchar), Width => 11);
  Ada.Text_IO.Put
  (Item => "               - Value in ASCII of current plaintext");
  Ada.Text_IO.New_line;
  Compute_Normal;
  Ada.Integer_Text_IO.Put(Item => Normal(1), Width => 4);
  Ada.Integer_Text_IO.Put(Item => Normal(2), Width => 8);
  Ada.Integer_Text_IO.Put(Item => Normal(3), Width => 8);
  Ada.Text_IO.Put(Item => "      - Normal vector -  fixed in this cipher");
  Ada.Text_IO.New_Line;
  Ada.Integer_Text_IO.Put(Item => S_1, Width => 4);
  Ada.Integer_Text_IO.Put(Item => S_2, Width => 8);
  Ada.Integer_Text_IO.Put(Item => S_3, Width => 8);
  Ada.Text_IO.Put
  (Item => "      - VeeZero - fixed in this cipher");
  Ada.Text_IO.New_Line;
  Ada.Integer_Text_IO.Put(Item => T_1, Width => 4);
  Ada.Integer_Text_IO.Put(Item => T_2, Width => 8);
  Ada.Integer_Text_IO.Put(Item => T_3, Width => 8);
  Ada.Text_IO.Put
  (Item => "      - VeeOne - fixed in this cipher.");
  Ada.Text_IO.New_Line;
  Compute_Normal;
  Ada.Integer_Text_IO.Put(Item => Normal(1), Width => 4);
  Ada.Integer_Text_IO.Put(Item => Normal(2), Width => 8);
  Ada.Integer_Text_IO.Put(Item => Normal(3), Width => 8);
  Ada.Text_IO.Put(Item => "      - Normal vector -  fixed in this cipher");
  Ada.Text_IO.New_Line;
  n :=(Character'Pos(NextChar));
  Ada.Integer_Text_IO.Put(Item => n, Width =>12);
  Ada.Text_IO.Put
  (Item => "              - face value 'n' of current plaintext in ASCII");
  Ada.Text_IO.New_Line;
  n := Number(Character'Pos(NextChar));  -- renumbered by Alice
  Ada.Integer_Text_IO.Put(Item => n, Width =>12);
  Ada.Text_IO.Put
  (Item => "              - rendered value of 'n'in the encryption alphabet");
  Compute_Position_Vector(Number => n);
  Ada.Text_IO.New_Line;
  Ada.Integer_Text_IO.Put(Item => Pn(1), Width => 8);
  Ada.Integer_Text_IO.Put(Item => Pn(2), Width => 8);
  Ada.Integer_Text_IO.Put(Item => Pn(3), Width => 8);
  Ada.Text_IO.Put(Item => "  - Position vector ('Pn') for this 'n'. ");
  Ada.Text_IO.New_Line;
  Ada.Integer_Text_IO.Put(Item => Hash_2(Count), Width => 8);
  Ada.Integer_Text_IO.Put(Item => Hash_11(Count), Width => 8);
  Ada.Integer_Text_IO.Put(Item => Hash_12(Count), Width => 8);
  Ada.Text_IO.Put
  (Item => "  - Change-of-origin vector to be given to this Pn item");
  Ada.Text_IO.New_Line;
    FOR I IN 1 .. 3 LOOP
      W(I):= Compose_CipherText_Items( Numin => I);
      Ada.Integer_Text_IO.Put(File => OutData, Item =>  W(I));
    END LOOP;
  Ada.Integer_Text_IO.Put( Item =>  W(1), Width => 9);
  Ada.Integer_Text_IO.Put( Item =>  W(2), Width => 8);
  Ada.Integer_Text_IO.Put( Item =>  W(3), Width => 8);
  Ada.Text_IO.Put(Item =>" - Ciphertext for this item of plaintext");
  Q:= W(1)REM 1000000;
  I_Num(Q) := I_Num(Q)+1;
--  Q:= W(2)REM 1000000;
--  I_Num(Q) := I_Num(Q)+1;
--  Q:= W(3)REM 1000000;
--  I_Num(Q) := I_Num(Q)+1;
--  Ada.Text_IO.New_Line;
--  Ada.Integer_Text_IO.Put(Item => AllTold, Width =>4);
--  Ada.Integer_Text_IO.Put(Item => Total, Width =>8);
--  Ada.Integer_Text_IO.Put(Item => InToto, Width =>8);
--  Ada.Text_IO.Put(Item => "      - Compares 'AllTold','Total','InToto' integrators'");
  Line_Number:= Line_Number+1;
  Ada.Text_IO.New_Line(1);
  Ada.Text_IO.Put(Item => "                          - Character number ");
  Ada.Integer_Text_IO.Put(Item => Line_Number, Width => 1);
  Ada.Text_IO.New_Line(1);
    IF Line_Number REM 12 = 0 THEN
      Ada.Text_IO.New_Line(1);
      Ada.Text_IO.Put(Item => "                       ");
      Ada.Text_IO.Put(Item => " # - press any key/return to continue > ");
      Ada.Text_IO.Get(Item => View);
    END IF;
--    IF W(2)REM 1000000 = 514681 THEN --repeated number in ciphertext say
--      Ada.Integer_Text_IO.Put (item => W(2) , Width => 20);
--      Ada.Text_IO.Get(Item => View);
--    END IF;
  Ada.Text_IO.New_Line;
  Ada.Text_IO.Put(Item => "  ---------------------------------------------------------------------------");
  END LOOP;
  Ada.Text_IO.Close(File => Outdata);
  Time_Ex_2;  -- time at end



^ permalink raw reply	[relevance 7%]

* Re: Help with an errant 'IF' statement please.
  @ 2014-11-29 15:05  4%   ` Austin Obyrne
    0 siblings, 1 reply; 200+ results
From: Austin Obyrne @ 2014-11-29 15:05 UTC (permalink / raw)


On Saturday, November 29, 2014 2:03:26 PM UTC, gautier...@hotmail.com wrote:
> Le samedi 29 novembre 2014 14:28:40 UTC+1, Austin Obyrne a écrit :
> 
> > This is an IF statement that just won't work and the same has happened in the past on other occasions in this very same program alone while working ok in other parts of the same program further on as well as being ok in other loops. 
> 
> Since Total doesn't change during the loop, the condition is either always True or always False. The IF works as always, but perhaps not in the way you expect... I guess you copy-pasted the IF statement from elsewhere, but then you should have "Line_Number" instead of "Total" to have a stop every 12 output lines.
> _________________________ 
> Gautier's Ada programming 
> http://gautiersblog.blogspot.com/search/label/Ada 
> NB: follow the above link for a valid e-mail address

I beg your pardon.

Total should not be there - it remained from my last experiment.

This is what I should have posted :-

Start here|:

Line_Number : Integer;  

Sentinel : CONSTANT Character:= '~';

Line_Number:= 0;
  
LOOP
  EXIT WHEN NextChar = Sentinel;
 
  Line_Number:= Line_Number+1;
  Ada.Text_IO.New_Line(1);
  Ada.Text_IO.Put(Item => "                          - Character number ");
  Ada.Integer_Text_IO.Put(Item => Line_Number, Width => 1);
  Ada.Text_IO.New_Line(1);
   
 
    IF Line_Number REM 12 = 0 THEN
      Ada.Text_IO.New_Line(1);
      Ada.Text_IO.Put(Item => "                       ");
      Ada.Text_IO.Put(Item => " # - press any key/return to continue > ");
      Ada.Text_IO.Get(Item => View);
    END IF;

  Ada.Text_IO.New_Line;
  Ada.Text_IO.Put(Item => "  ----------------------------------------------------------------");
  END LOOP;

Sorry for confusing matters, please continue if you will - Austin

^ permalink raw reply	[relevance 4%]

* Help with an errant 'IF' statement please.
@ 2014-11-29 13:28  3% Austin Obyrne
    0 siblings, 1 reply; 200+ results
From: Austin Obyrne @ 2014-11-29 13:28 UTC (permalink / raw)


A subset of a larger program is shown below.

This is an IF statement that just won't work and the same has happened in the past on other occasions in this very same program alone while working ok in other parts of the same program further on as well as being ok in other loops. 

It works fine also in other programs in different loops but for some unknown (to me) reason it just won't work here in this loop on this occasion.

I have tried everything to no avail.

Maybe there is some basic syntax that I am contravening in this type of Loop.

Your usual help would be greatly appreciated.

The 'GET' function is intended to stall the run of the loop for viewing of the data.

(Start looking here Please:)

Line_Number : Integer;  

Sentinel : CONSTANT Character:= '~';

Line_Number:= 0;
  
LOOP
  EXIT WHEN NextChar = Sentinel;
  Line_Number:= Line_Number+1;
  Ada.Text_IO.New_Line(1);
  Ada.Text_IO.Put(Item => "                          - Character number ");
  Ada.Integer_Text_IO.Put(Item => Line_Number, Width => 1);
  Ada.Text_IO.New_Line(1);
   
 
    IF Total REM 12 = 0 THEN
      Ada.Text_IO.New_Line(1);
      Ada.Text_IO.Put(Item => "                       ");
      Ada.Text_IO.Put(Item => " # - press any key/return to continue > ");
      Ada.Text_IO.Get(Item => View);
    END IF;

  Ada.Text_IO.New_Line;
  Ada.Text_IO.Put(Item => "  ----------------------------------------------------------------");
  END LOOP;
  ?

Austin O' Byrne - aka adacrypt. 

^ permalink raw reply	[relevance 3%]

* Re: Question about reference types
  2014-10-27 12:09  4% Question about reference types rkodinets
@ 2014-10-27 18:09  0% ` Martyn Pike
  0 siblings, 0 replies; 200+ results
From: Martyn Pike @ 2014-10-27 18:09 UTC (permalink / raw)


On 27/10/2014 12:09, rkodinets@gmail.com wrote:
> with Ada.Text_IO; use Ada.Text_IO;
> with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
>
> procedure Ada_Test is
>
>     type Obj is record
>        A : aliased Integer;
>     end record;
>
>     type Obj_Access is access Obj;
>
>     type Accessor (Data : access constant Integer) is null record with

This is where the error is.  Data is constant.

>       Implicit_Dereference => Data;
>
>     function Get_Int (This : Obj_Access) return Accessor is
>     begin
>        return Accessor'(Data => This.A'Access);
>     end Get_Int;
>
>     X : Obj_Access := new Obj'(A => 22);
> begin
>     Get_Int(X).Data.all := 33; -- Error: left hand side of assignment must be a variable
>     Get_Int(X) := 33;          -- No error.
>     Put(X.A);                  -- This gives 33.
>     New_Line;
> end Ada_Test;


^ permalink raw reply	[relevance 0%]

* Question about reference types
@ 2014-10-27 12:09  4% rkodinets
  2014-10-27 18:09  0% ` Martyn Pike
  0 siblings, 1 reply; 200+ results
From: rkodinets @ 2014-10-27 12:09 UTC (permalink / raw)


Hello,
I'm Ada novice and I have some trouble with understanding the Implicit_Dereference aspect feature.

I tried to use the feature with a read-only-access accessor object.

Consider the following code:

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Ada_Test is
   
   type Obj is record
      A : aliased Integer;
   end record;
   
   type Obj_Access is access Obj;
   
   type Accessor (Data : access constant Integer) is null record with
     Implicit_Dereference => Data;
   
   function Get_Int (This : Obj_Access) return Accessor is
   begin
      return Accessor'(Data => This.A'Access);
   end Get_Int;
   
   X : Obj_Access := new Obj'(A => 22);
begin
   Get_Int(X).Data.all := 33; -- Error: left hand side of assignment must be a variable
   Get_Int(X) := 33;          -- No error.
   Put(X.A);                  -- This gives 33.
   New_Line;
end Ada_Test;

The RM clearly states that "A generalized_reference denotes a view equivalent to that of a dereference of the reference discriminant of the reference object". Hence, if the "reference discriminant" (Data) of the "reference object" (object of type Accessor, returned by Get_Int) has an "access constant" type and, consequently, grants only read access to the object, so should the "generalized reference", which (if I understand correcly) is Get_Int(X) inside of an assignment statement. So, I expected the compiler to print an error, just like with the normal read-only accessor. To my surprise, it compiled just fine, and the new value was assigned to the object.

Why is it so?

And one more related question. Some resourses on the Net state that usage of Implicit_Dereferense aspect make function (Get_Int in this example) overloaded. If this is the case, what is the return type of the second function? As far as I understand, it can't be Integer, because it would mean that it returns a copy of an object, and we can't change the value of the object through its copy. Is it "access Integer" which is then dereferenced implicitly? Then why it is not "access constant Integer", which would be more logical in this case? 

Thanks.


^ permalink raw reply	[relevance 4%]

* Re: confusion about message passing between the tasks
  @ 2014-10-25 23:26  4%       ` compguy45
  0 siblings, 0 replies; 200+ results
From: compguy45 @ 2014-10-25 23:26 UTC (permalink / raw)


 Can anyone tell me why i am getting zero printed to the screen even though i am passing 5?


 2 use Ada.Text_IO, Ada.Integer_Text_IO;
  3 
  4 with Ada.Calendar; use Ada.Calendar;
  5 
  6 procedure strib1 is
  7 
  8 task type Counter_Task is
  9    entry Get (Value : out Integer);
 10 end Counter_Task;
 11 
 12 
 13 p: Counter_Task;
 14 i : Integer;
 15      
 16      
 17      
 18 task body Counter_Task is
 19         V : Integer := 0;
 20     begin
 21         loop
 22             select
 23                 accept Get (Value : out Integer) do
 24                     put("Value of parametar passed in is ");put(Value); 
                        --Why am i getting zero printed???
 25                     Value := V;
 26                     V     := V + 1;
 27                 end Get;
 28             or  
 29                 terminate;
 30             end select;
 31         end loop;
 32     end Counter_Task;
 33 
 34 begin
 35   i := 5;
 36   p.Get(i); 
 37 




^ permalink raw reply	[relevance 4%]

* Gnat Pro Cross compiling
@ 2014-10-16 12:55  4% Nahro Nadir
  0 siblings, 0 replies; 200+ results
From: Nahro Nadir @ 2014-10-16 12:55 UTC (permalink / raw)


I am trying to use gnat pro as a cross compiler which use arm-eabi toolchain, but it cannot recognize any Ada packages!!

Here is compilation result:


        5:6 "ada.calendar" is not a predefined library unit
        2:6 "ada.direct_io" is not a predefined library unit
        8:6 "ada.float_text_io" is not a predefined library unit
        7:6 "ada.integer_text_io" is not a predefined library unit
        10:6 "ada.numerics" is not a predefined library unit
        2:6 "ada.text_io" is not a predefined library unit
        2:6 "bmp (spec)" depends on "ada.direct_io (spec)"
        2:6 "bmp (spec)" depends on "ada.text_io (spec)"
        3:6 "serial_net (spec)" depends on "gnat.sockets (spec)"
        2:6 "stream (body)" depends on "bmp (spec)"
        3:6 "stream (body)" depends on "serial_net (spec)"
        3:6 file "g-socket.ads" not found



^ permalink raw reply	[relevance 4%]

* Re: passing messages between the tasks
  2014-10-14  1:17  5% passing messages between the tasks compguy45
@ 2014-10-14  1:49  0% ` Adam Beneschan
  0 siblings, 0 replies; 200+ results
From: Adam Beneschan @ 2014-10-14  1:49 UTC (permalink / raw)


On Monday, October 13, 2014 6:17:29 PM UTC-7, comp...@gmail.com wrote:
> I understand in this example that calling tasks(main or environmental task) is passing id value to 2 tasks...In regarding to code below I have 2 question and was hoping someone can answer....
> 
>   1 with Ada.Text_IO, Ada.Integer_Text_IO;
>   2 use Ada.Text_IO, Ada.Integer_Text_IO;
>   3 
>   4 procedure SomeProcedure is
>   5 
>   6 task type lamp is
>   7    entry reset(id : Integer);
>   8 end lamp;
>   9 
>  10 lamps : array (1..6) of lamp;
>  11 
>  12    task body lamp is
>  13    begin
>  14       Put_Line("Body of task lamp");
>  15       accept reset(id : Integer) do
>  16         put("inside reset");
>  17         put(id);
>  18         New_Line;
>  19       end reset;
>  20       delay 4.0;
>  21    put("after accept");
>  22    end lamp;
>  23 
>  24 begin
>  25    lamps(1).reset(id => 1);
>  26    lamps(2).reset(id => 2);
>  27 end SomeProcedure;
> 
> 1. How would would these 2 tasks send message back to main? For example how would each of these two lamp tasks send "i received call to my acceptstatement");

An entry can have OUT (or IN OUT) parameters.  If you want the "accept" to send something back to the task that calls the entry, define the entry with an OUT parameter, and set this parameter inside the ACCEPT statement.

For a String, the problems with using a String as an OUT parameter are the same as for procedures--you can't really return a variable-length string this way.  However, you can use Ada.Strings.Unbounded.Unbounded_String:

entry reset(id : Integer; message : out Unbounded_String);

and then in the accept statement:

message := To_Unbounded_String("I received my call");

and then in the main:

    lamps(1).reset(id=>1, message=>The_Message);

where The_Message is a variable or whatever.


> 2. If there are some variables inside the body of the task to be saved and they might be different for each of these tasks how to save these values?

You'll have to be clearer on what you mean by this.

                               -- Adam

^ permalink raw reply	[relevance 0%]

* passing messages between the tasks
@ 2014-10-14  1:17  5% compguy45
  2014-10-14  1:49  0% ` Adam Beneschan
  0 siblings, 1 reply; 200+ results
From: compguy45 @ 2014-10-14  1:17 UTC (permalink / raw)


I understand in this example that calling tasks(main or environmental task) is passing id value to 2 tasks...In regarding to code below I have 2 question and was hoping someone can answer....

  1 with Ada.Text_IO, Ada.Integer_Text_IO;
  2 use Ada.Text_IO, Ada.Integer_Text_IO;
  3 
  4 procedure SomeProcedure is
  5 
  6 task type lamp is
  7    entry reset(id : Integer);
  8 end lamp;
  9 
 10 lamps : array (1..6) of lamp;
 11 
 12    task body lamp is
 13    begin
 14       Put_Line("Body of task lamp");
 15       accept reset(id : Integer) do
 16         put("inside reset");
 17         put(id);
 18         New_Line;
 19       end reset;
 20       delay 4.0;
 21    put("after accept");
 22    end lamp;
 23 
 24 begin
 25    lamps(1).reset(id => 1);
 26    lamps(2).reset(id => 2);
 27 end SomeProcedure;

1. How would would these 2 tasks send message back to main? For example how would each of these two lamp tasks send "i received call to my acceptstatement");

2. If there are some variables inside the body of the task to be saved and they might be different for each of these tasks how to save these values?


^ permalink raw reply	[relevance 5%]

* Re: permutation of strings
  @ 2014-10-07 11:22  5%   ` Brian Drummond
  0 siblings, 0 replies; 200+ results
From: Brian Drummond @ 2014-10-07 11:22 UTC (permalink / raw)


On Mon, 06 Oct 2014 22:38:25 -0700, mockturtle wrote:

> On Tuesday, October 7, 2014 7:23:53 AM UTC+2, Stribor40 wrote:
>> I have created this code using some online tutorials and some examples
>> that i tried to learn... i havent been able to find whats wrong with my
>> code....i am guessing what my variable j is somehow getting reset
>> during the recursive calls...
>> 
>> i have been trying to retrace recursive calls by writing each call on
>> the on the paper but i get lost trying to track it down......
>> 
>> my code spits out numbers...123 123 123 123 123 123 instead of 123 132
>> 213 231 321 312 so i was hoping if someone can take a look and suggest
>> how to fix this....
>> 
>> i pasted the code here it is ready to be compiled and there are no
>> errors when it is compiled....http://pastebin.com/rDF46RbR
> 
> At the moment I do not have a compiler at hand (I'm having breakfast
> :-), but I see at least one strange thing in your code: in the loop "for
> Index ...." I would expect calls to "change(s, i, Index)" rather than
> "change(s, i, j)".  With the latter there is no difference between
> different iterations and this could give rise to your error.

Nailed it by inspection!

> By the way, there is no need to have j declared "in out" in Change,
> since j is not changed. Moreover, I suspect that with the "in out"
> specification the compiler will complain, since you cannot change a loop
> index.

Having corrected the real bug, it did complain...

If I might add a couple more style changes:
1) Eliminate global variable "tmp" which should be local to procedure 
"change" 
2) Eliminate global variable "Start" and potential for off-by-1 bugs, by 
using the array attributes in the main call to Perms

Works as I would expect anyway.

- Brian
---------------------------------------------

with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;

procedure permutation is

  str : String := "123";

  procedure perms (s :  in out String; i : in Integer; n : in Integer);
  procedure change (s : in out String; i : in Integer; j : in Integer);

  procedure  perms (s : in out String; i : in Integer; n : in Integer) is
    j : Integer := i;
  begin
    if i = n then
      put(s);
      New_Line;
    else
      for Index in j..n loop
        change(s,i,index); 
        perms(s,i+1,n);
        change(s,i,index); 
      end loop;
    end if;
  end perms;
  
 
  procedure  change (s : in out String; i : in  Integer; j : in Integer) 
is
    tmp : Character;
  begin
    tmp  := s(i);
    s(i) := s(j);
    s(j) := tmp;
 end change;

begin
    perms(str,str'first,str'last);
end permutation;



^ permalink raw reply	[relevance 5%]

* Concurrency in Ada
@ 2014-09-07 12:29  5% Stribor40
  0 siblings, 0 replies; 200+ results
From: Stribor40 @ 2014-09-07 12:29 UTC (permalink / raw)


I have this program from online tutorial that says that tasks will run as soon as program starts. My question is when does this program starts on what line if code
WITH Ada.Text_IO;                  --  Include Text_IO Library
WITH Ada.Integer_Text_IO;          --  Include Integer Text_IO Library
PROCEDURE task_demo_01 IS
                                   --  Task Type Specification
     TASK TYPE intro_task (message : Integer);

     TASK BODY intro_task IS       --  Task Body Definition
     BEGIN
          FOR count IN 1..5 LOOP
               Ada.Text_IO.put (Item => "Display from Task ");
               Ada.Integer_Text_IO.put (Item => message, Width => 1);
               Ada.Text_IO.new_line;
          END LOOP;
     END intro_task;
     --  Unlike procedures, these tasks are not called.
     --  These three tasks are activated once the program begins.
     Task_1 : intro_task (message => 1);
     Task_2 : intro_task (message => 2);
     Task_3 : intro_task (message => 3);
BEGIN                                           
     NULL;                                   
END task_demo_01;

Do tasks run all at same tine or they are scheduled by OS which would mean anytime you run this program output would be different? 


^ permalink raw reply	[relevance 5%]

* Re: Problem with output using Ada.Text_IO.Put
  2014-07-19 21:37  5% Problem with output using Ada.Text_IO.Put junior learning ADA
  2014-07-19 22:10  6% ` Jerry
  2014-07-19 23:58  0% ` Jeffrey Carter
@ 2014-07-20  5:22  0% ` Niklas Holsti
  2 siblings, 0 replies; 200+ results
From: Niklas Holsti @ 2014-07-20  5:22 UTC (permalink / raw)


On 14-07-20 00:37 , junior learning ADA wrote:
> I am starting to learn ADA and I have installed Adacore gnat 2014. 

Welcome to the Ada community! And don't be offended if some of us insist
that it should be spelled Ada instead of ADA. This spelling thing is
something of an "in-joke" here. Now that you have been subjected to it,
you can consider yourself initiated into the community.

> I am using the source codes from M.B. Feldman and E.B. Koffman,
> Ada 95 Problem Solving and Program Design, 3rd edition.
> 
> In this respect, there appears to be a problem with Ada.Text_IO.Put
> and Ada.Integer_Text_IO.Get. The issue is that the text output
> only appears after the Ada.Integer_Text_IO.Get (Item => Nickels);

As others have answered, interactive Text_IO should not behave in that
way, but should behave as you expect it to do. (However -- and this is a
question for the other responders -- I did not yet find where in the Ada
Reference Manual this interactive behaviour is specified.)

> Please see extract from program:
> 
> BEGIN -- Coin_Collection
> 
>   -- prompt user for number of nickels and pennies
>   Ada.Text_IO.Put (Item => "How many nickels do you have? ");
>   Ada.Integer_Text_IO.Get (Item => Nickels);
>   Ada.Text_IO.Put (Item => "How many pennies do you have? ");
>   Ada.Integer_Text_IO.Get (Item => Pennies);
>   Ada.Text_IO.New_Line;
> 
> 
> However, when I run the program the text output appears after the questions. See below:
> /Users/francois/Documents/ADA/test/fk3-w95/coin_collection
> 1
> 2
> How many nickels do you have? How many pennies do you have? 
> [2014-07-19 22:05:16] process terminated successfully, elapsed time: 16.28s

It seems as if the process that executes your Ada program is treating
the Text_IO standard-output channel as a block-buffered channel, and is
not flushing the collected output when the program asks for some input
on the standard-input channel, as should happen for interactive,
non-buffered channels.

Are you running the program from a normal shell in a normal command
window, or in some special way? Which OS are you using? Are you using
some output-collecting tool such as "tee"? Please show us the command
line you use to run your program.

To understand the problem better, you could make some experiments:

- Try using Ada.Text_IO.Put_Line instead of Put (or, alternatively, add
a call of Ada.Text_IO.New_Line after each Put call). This experiment
should show us if your system treats standard-output as line-buffered
(but from the output you display, this is not the case).

- Try adding a call of Ada.Text_IO.Flush after every call to Put, at the
point where you expect the output from the Put to be visible as a prompt
for the user's input. This may counteract the output buffering that, for
some reason, is happening in your environment.


-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
      .      @       .

^ permalink raw reply	[relevance 0%]

* Re: Problem with output using Ada.Text_IO.Put
  2014-07-19 21:37  5% Problem with output using Ada.Text_IO.Put junior learning ADA
  2014-07-19 22:10  6% ` Jerry
@ 2014-07-19 23:58  0% ` Jeffrey Carter
  2014-07-20  5:22  0% ` Niklas Holsti
  2 siblings, 0 replies; 200+ results
From: Jeffrey Carter @ 2014-07-19 23:58 UTC (permalink / raw)


On 07/19/2014 02:37 PM, junior learning ADA wrote:
> I am starting to learn ADA and I have installed Adacore gnat 2014.

Good. Is that the American Dental Association or the Americans with Disabilities 
Act that you're learning? Ada is a woman's name (Ada King, Countess of Lovelace, 
who wrote programs for Babbage's Analytical Engine), not an acronym.

> BEGIN -- Coin_Collection
>
>    -- prompt user for number of nickels and pennies
>    Ada.Text_IO.Put (Item => "How many nickels do you have? ");
>    Ada.Integer_Text_IO.Get (Item => Nickels);
>    Ada.Text_IO.Put (Item => "How many pennies do you have? ");
>    Ada.Integer_Text_IO.Get (Item => Pennies);
>    Ada.Text_IO.New_Line;
>
>
> However, when I run the program the text output appears after the questions. See below:
> /Users/francois/Documents/ADA/test/fk3-w95/coin_collection
> 1
> 2
> How many nickels do you have? How many pennies do you have?
> [2014-07-19 22:05:16] process terminated successfully, elapsed time: 16.28s

That's very odd. I can't say that I've seen that behavior before.

> Is the issue coming from using a newer version of ADA?

No, Ada.Text_IO should work the same.

-- 
Jeff Carter
"All citizens will be required to change their underwear
every half hour. Underwear will be worn on the outside,
so we can check."
Bananas
29

^ permalink raw reply	[relevance 0%]

* Re: Problem with output using Ada.Text_IO.Put
  2014-07-19 21:37  5% Problem with output using Ada.Text_IO.Put junior learning ADA
@ 2014-07-19 22:10  6% ` Jerry
  2014-07-19 23:58  0% ` Jeffrey Carter
  2014-07-20  5:22  0% ` Niklas Holsti
  2 siblings, 0 replies; 200+ results
From: Jerry @ 2014-07-19 22:10 UTC (permalink / raw)


Works for me.

with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure textfromcla is
    Nickels, Pennies : Integer;
begin
    Ada.Text_IO.Put (Item => "How many nickels do you have? "); 
    Ada.Integer_Text_IO.Get (Item => Nickels); 
    Ada.Text_IO.Put (Item => "How many pennies do you have? "); 
    Ada.Integer_Text_IO.Get (Item => Pennies); 
    Ada.Text_IO.New_Line;
end textfromcla;

causes

How many nickels do you have? 3
How many pennies do you have? 5

Jerry

^ permalink raw reply	[relevance 6%]

* Problem with output using Ada.Text_IO.Put
@ 2014-07-19 21:37  5% junior learning ADA
  2014-07-19 22:10  6% ` Jerry
                   ` (2 more replies)
  0 siblings, 3 replies; 200+ results
From: junior learning ADA @ 2014-07-19 21:37 UTC (permalink / raw)


I am starting to learn ADA and I have installed Adacore gnat 2014. 

I am using the source codes from M.B. Feldman and E.B. Koffman, Ada 95 Problem Solving and Program Design, 3rd edition.

In this respect, there appears to be a problem with Ada.Text_IO.Put and Ada.Integer_Text_IO.Get. The issue is that the text output only appears after the Ada.Integer_Text_IO.Get (Item => Nickels);

Please see extract from program:

BEGIN -- Coin_Collection

  -- prompt user for number of nickels and pennies
  Ada.Text_IO.Put (Item => "How many nickels do you have? ");
  Ada.Integer_Text_IO.Get (Item => Nickels);
  Ada.Text_IO.Put (Item => "How many pennies do you have? ");
  Ada.Integer_Text_IO.Get (Item => Pennies);
  Ada.Text_IO.New_Line;


However, when I run the program the text output appears after the questions. See below:
/Users/francois/Documents/ADA/test/fk3-w95/coin_collection
1
2
How many nickels do you have? How many pennies do you have? 
[2014-07-19 22:05:16] process terminated successfully, elapsed time: 16.28s

I guess my explanation is not very clear, but what I would have expected the program to do is:
How many nickels do you have? 
(then we enter 1 for example)
How many pennies do you have? 
(then we enter 2 for example)

Is the issue coming from using a newer version of ADA?

Francois


^ permalink raw reply	[relevance 5%]

* Re: Technical Question.
  2014-06-09 12:50  0% ` Austin Obyrne
@ 2014-06-09 17:54  5%   ` Austin Obyrne
  0 siblings, 0 replies; 200+ results
From: Austin Obyrne @ 2014-06-09 17:54 UTC (permalink / raw)


On Monday, June 9, 2014 1:50:09 PM UTC+1, Austin Obyrne wrote:
> On Monday, June 9, 2014 1:15:46 PM UTC+1, Austin Obyrne wrote: > A cryptographic cipher I have written is demonstrable by mathematical proof to be the ultimate in cryptographic strength i.e. it is of "Theoretically Unbreakable Class" in official crypto terminology. Although the algorithm is written in stone by analogy I always avail of any extra entanglement (usually considerable) that may up for grabs at the programming stage when I write any cipher programs. This is often a property of the Ada language alone quite part from the general cipher mathematical algorithm. Demonstration. This is an array below that loads the 'I' coefficients of a vector (the J and K coefficients are elsewhere also in other arrays not shown here). *The elements of the array reside in off-page (In the folder) reservoirs called 'packages' (Case Statements) when not required and are loaded into the ready-use array called 'E' initially at boot-up time of the computer. The procedure below scrambles the elements of the array called 'E' by positional reshuffling them from their original assigned position and repositioning them by controlled means in another array called 'EE'. That procedure is safely invertible at decryption time and so far this ploy has never let me down. The elements of 'E' are scrambled while being loaded into the array 'EE' and are later called *sequentially from 'EE' for use by the main program at run-time as key material. Question. Is this ploy of scrambling key material by this means legit in Ada - i.e. is it sanctioned by the Ada reference manual ? i.e. is it acceptable to you guys as *proper Ada orogramming practice?. I intend to go on using it but I would like to know what you think. This ploy is my own invention. I would be grateful for your replies. -------------------------------------------------------------------------------- PROCEDURE Load_n_Scramble_Normal_Vector_I_Coefficients IS -- Pre: Normal_Vector_I_Coefficients_ Package is defined. -- Post: These coefficients are stored in ready use arrays at runtime. BEGIN -- Load_Normal_Vector_I_Coefficients FOR I IN 1 .. 1000 LOOP E(I) := Normal_Vector_I_Coefficients.NumberExchange(Numin => I); EE(I) := Normal_Vector_I_Coefficients.NumberExchange(Numin => I); -- Q := E(I); -- statistical data collection -- I_Num(Q):= I_Num(Q)+1; -- these numbers tested ok for randomness END LOOP; X := 0; FOR J IN 1 .. iterances LOOP FOR I IN REVERSE X+1 .. X+increment LOOP X:=X+1; EE(X) := E(I); -- Ada.Text_IO.New_Line;-- -- Ada.Integer_Text_IO.Put(Item => E(X), Width => 8);-- -- Ada.Integer_Text_IO.Put(Item => EE(X), Width => 8);-- END LOOP; -- Ada.Text_IO.New_Line;-- END LOOP; -- Ada.Integer_Text_IO.Get(Item => View); -- halts program to allow view.-- END Load_n_Scramble_Normal_Vector_I_Coefficients; ------------------------------------ ------------------------------------------ Thanks in anticipation of your help, Austin O'Byrne - adacrypr Forgot to include these scrambling parameters, Increment : CONSTANT Integer := 20; Iterances : CONSTANT Integer := 50; -- Normals scrambling -- Increment * Iterances <= 1000. -- specifies the scope of the scrambling data. Austin

 Late annotation.

 X := 0; 
  FOR J IN 1 .. iterances LOOP 
  FOR I IN REVERSE X+1 .. X+increment LOOP 
    X:=X+1; 
    EE(X) := E(I); 
--  Ada.Text_IO.New_Line;-- 
--  Ada.Integer_Text_IO.Put(Item => E(X), Width => 8);-- 
--  Ada.Integer_Text_IO.Put(Item => EE(X), Width => 8);-- 
  END LOOP; 
--  Ada.Text_IO.New_Line;-- 
  END LOOP; 
--  Ada.Integer_Text_IO.Get(Item => View);  -- halts program to allow view.-- 
END Load_n_Scramble_Normal_Vector_I_Coefficients; 

For this setting of scrambling parameters i.e increment := 20,iterances := 50

The inner loop puts element - 
No 20 of 'E' into position 1 of 'EE'
No 19 of 'e' goes to position 2 of 'EE' and so on to completion of the inside LOOP and all elements from 20 to 1 have been transposed.

The outside loop repeats that 50 times so as to position all of the elements of 'E' in displaced positions in 'EE'.

What's bothering me is this.  Ada has some very distinct rules about what can be done with operating on arrays and strings.  Although my method works does it do so within all of these rules and not be just a lucky bug ????

adacrypt

^ permalink raw reply	[relevance 5%]

* Re: Technical Question.
  2014-06-09 12:15  4% Technical Question Austin Obyrne
@ 2014-06-09 12:50  0% ` Austin Obyrne
  2014-06-09 17:54  5%   ` Austin Obyrne
  0 siblings, 1 reply; 200+ results
From: Austin Obyrne @ 2014-06-09 12:50 UTC (permalink / raw)


On Monday, June 9, 2014 1:15:46 PM UTC+1, Austin Obyrne wrote:
> A cryptographic cipher I have written is demonstrable by mathematical proof to be the ultimate in cryptographic strength i.e. it is of "Theoretically Unbreakable Class" in official crypto terminology. Although the algorithm is written in stone by analogy I always avail of any extra entanglement (usually considerable) that may up for grabs at the programming stage when I write any cipher programs. This is often a property of the Ada language alone quite part from the general cipher mathematical algorithm. Demonstration. This is an array below that loads the 'I' coefficients of a vector (the J and K coefficients are elsewhere also in other arrays not shown here). *The elements of the array reside in off-page (In the folder) reservoirs called 'packages' (Case Statements) when not required and are loaded into the ready-use array called 'E' initially at boot-up time of the computer. The procedure below scrambles the elements of the array called 'E' by positional reshuffling them from their original assigned position and repositioning them by controlled means in another array called 'EE'. That procedure is safely invertible at decryption time and so far this ploy has never let me down. The elements of 'E' are scrambled while being loaded into the array 'EE' and are later called *sequentially from 'EE' for use by the main program at run-time as key material. Question. Is this ploy of scrambling key material by this means legit in Ada - i.e. is it sanctioned by the Ada reference manual ? i.e. is it acceptable to you guys as *proper Ada orogramming practice?. I intend to go on using it but I would like to know what you think. This ploy is my own invention. I would be grateful for your replies. -------------------------------------------------------------------------------- PROCEDURE Load_n_Scramble_Normal_Vector_I_Coefficients IS -- Pre: Normal_Vector_I_Coefficients_ Package is defined. -- Post: These coefficients are stored in ready use arrays at runtime. BEGIN -- Load_Normal_Vector_I_Coefficients FOR I IN 1 .. 1000 LOOP E(I) := Normal_Vector_I_Coefficients.NumberExchange(Numin => I); EE(I) := Normal_Vector_I_Coefficients.NumberExchange(Numin => I); -- Q := E(I); -- statistical data collection -- I_Num(Q):= I_Num(Q)+1; -- these numbers tested ok for randomness END LOOP; X := 0; FOR J IN 1 .. iterances LOOP FOR I IN REVERSE X+1 .. X+increment LOOP X:=X+1; EE(X) := E(I); -- Ada.Text_IO.New_Line;-- -- Ada.Integer_Text_IO.Put(Item => E(X), Width => 8);-- -- Ada.Integer_Text_IO.Put(Item => EE(X), Width => 8);-- END LOOP; -- Ada.Text_IO.New_Line;-- END LOOP; -- Ada.Integer_Text_IO.Get(Item => View); -- halts program to allow view.-- END Load_n_Scramble_Normal_Vector_I_Coefficients; ------------------------------------ ------------------------------------------ Thanks in anticipation of your help, Austin O'Byrne - adacrypr

Forgot to include these scrambling parameters,

  Increment : CONSTANT Integer := 20;
  Iterances : CONSTANT Integer := 50;
  -- Normals scrambling
  -- Increment * Iterances <= 1000. -- specifies the scope of the scrambling 
data.

Austin

^ permalink raw reply	[relevance 0%]

* Technical Question.
@ 2014-06-09 12:15  4% Austin Obyrne
  2014-06-09 12:50  0% ` Austin Obyrne
  0 siblings, 1 reply; 200+ results
From: Austin Obyrne @ 2014-06-09 12:15 UTC (permalink / raw)


A cryptographic cipher I have written is demonstrable by mathematical proof to be the ultimate in cryptographic strength i.e. it is of "Theoretically Unbreakable Class" in official crypto terminology.  Although the algorithm is written in stone by analogy I always avail of any extra entanglement (usually considerable) that may up for grabs at the programming stage when I write any cipher programs.  This is often a property of the Ada language alone quite part from the general cipher mathematical algorithm.

Demonstration.

This is an array below that loads the 'I' coefficients of a vector (the J and K coefficients are elsewhere also in other arrays not shown here).

*The elements of the array reside in off-page (In the folder) reservoirs called 'packages' (Case Statements) when not required and are loaded into the ready-use array called 'E' initially at boot-up time of the computer.

The procedure below scrambles the elements of the array called 'E' by positional reshuffling them from their original assigned position and repositioning them by controlled means in another array called 'EE'.  That procedure is safely invertible at decryption time and so far this ploy has never let me down.  The elements of 'E' are scrambled while being loaded into the array 'EE' and are later called *sequentially from 'EE' for use by the main program at run-time as key material.

Question.

Is this ploy of scrambling key material by this means legit in Ada - i.e. is it sanctioned by the Ada reference manual ? i.e. is it acceptable to you guys as *proper Ada orogramming practice?.

I intend to go on using it but I would like to know what you think.

This ploy is my own invention.

I would be grateful for your replies.

--------------------------------------------------------------------------------  PROCEDURE Load_n_Scramble_Normal_Vector_I_Coefficients IS
  -- Pre: Normal_Vector_I_Coefficients_ Package is defined.
  -- Post: These coefficients are stored in ready use arrays at runtime. 

BEGIN  -- Load_Normal_Vector_I_Coefficients

  FOR I IN 1 .. 1000 LOOP
    E(I)  := Normal_Vector_I_Coefficients.NumberExchange(Numin => I);
    EE(I) := Normal_Vector_I_Coefficients.NumberExchange(Numin => I);
--    Q := E(I); -- statistical data collection
--    I_Num(Q):= I_Num(Q)+1; -- these numbers tested ok for randomness
  END LOOP;
    X := 0;
  FOR J IN 1 .. iterances LOOP
  FOR I IN REVERSE X+1 .. X+increment LOOP
    X:=X+1;
    EE(X) := E(I);
--  Ada.Text_IO.New_Line;--
--  Ada.Integer_Text_IO.Put(Item => E(X), Width => 8);--
--  Ada.Integer_Text_IO.Put(Item => EE(X), Width => 8);--
  END LOOP;
--  Ada.Text_IO.New_Line;--
  END LOOP;
--  Ada.Integer_Text_IO.Get(Item => View);  -- halts program to allow view.--
END Load_n_Scramble_Normal_Vector_I_Coefficients;

 ------------------------------------ ------------------------------------------

Thanks in anticipation of your help,

Austin O'Byrne - adacrypr


^ permalink raw reply	[relevance 4%]

* Re: Bug or feature?
  @ 2014-05-14 20:15  5%   ` Adam Beneschan
  0 siblings, 0 replies; 200+ results
From: Adam Beneschan @ 2014-05-14 20:15 UTC (permalink / raw)


On Wednesday, May 14, 2014 12:57:47 PM UTC-7, Adam Beneschan wrote:

> It does appear that GNAT may not always check the range properly when a
> function whose result is Positive tries to return a negative value due to
> overflow.  That would explain why the recursive version doesn't get an
> exception.

Here's an example:

with Ada.Integer_Text_IO;
with Ada.Text_IO;

procedure Test is
   Result : Integer;

   function Add (X1, X2 : Positive) return Positive is
   begin
      return X1 + X2;
   end Add;

   function Multiply (X1, X2 : Positive) return Positive is
   begin
      return X1 * X2;
   end Multiply;

begin
   Result := Add(2_000_000_000, 2_000_000_000);
   Ada.Integer_Text_IO.Put (Item => Result, Width => 1);
   Result := Multiply(6, 2_000_000_000);
   Ada.Integer_Text_IO.Put (Item => Result, Width => 1);
end Test;

Compiled without -gnato.  The result is that a negative number is output after the call to Add, but the call to Multiply raises an exception.  So it looks like when the function result is Positive, a "return" that returns the result of an addition doesn't check to make sure the result is in range (when overflow is possible), but a "return" that returns the result of a multiplication does check.  That would also explain why the original Buffer_Overflow test case works but the recursive Fibonacci routine doesn't.

                                 -- Adam


^ permalink raw reply	[relevance 5%]

* Bug or feature?
@ 2014-05-14 19:06  6% Laurent
    0 siblings, 1 reply; 200+ results
From: Laurent @ 2014-05-14 19:06 UTC (permalink / raw)


Hi

While studying recursion I tried to develop an iterative version of the fibonacci sequence.

It works but on N>47 the function outputs negative numbers,buffer overflow. No difference between my iterative version and the recursive one given in the book (recursion is quite slow...).

Build a small test program which throws a Constraint error. So why does the test functions correctly where as the fibonacci program doesn't?

I have added an Exception for the buffer overflow to the iterative version to check if this solves the problem and it does.

Positive is defined as : subtype Positive is Integer range 1 .. Integer'Last;
So if the result gets negative it should raise an constraint error without needing to add a raise myself?

Output of fibonacci:

Please enter an integer (>= 1) > 50

The fibonacci sequence for N = 50 is: 
1
1
2
3
5
8
13
21
34
55
.
.
.
1134903170
1836311903
-1323752223  <==
512559680
-811192543 <==
-298632863 <==
[2014-05-14 20:57:08] process terminated successfully (elapsed time: 02.29s)

Output of buffer_overflow test:

enter an integer: 10

raised CONSTRAINT_ERROR : buffer_overflow.adb:11 range check failed 
(normal 10*2*10^9 = too big for 32 bit int)
[2014-05-14 20:55:07] process exited with status 1 (elapsed time: 01.51s)

Thanks

Laurent

with Ada.Text_IO;
with Ada.Integer_Text_IO;

procedure Test_Fibonacci is
   N : Positive;
   Result : Positive := 1;
   Buffer_Overflow : exception;

   function Fibonacci_Iter (N : in Positive) return Positive is
   -- Returns the Nth Fibonacci number, computed iteratively
   -- Pre : N is defined and N >= 1
   -- Post: returns N!

      First : Positive := 1;
      Second : Positive := 1;

   begin -- Fibonacci Iteration

      if N = 1 or N = 2 then
         return Result;
      else
         for Count in 3 .. N loop
            Result := First + Second;
            First := Second;
            Second := Result;
         end loop;
         if Result'Valid then            
            return Result;
         else
            raise Buffer_Overflow;
         end if;            
      end if;
   end Fibonacci_Iter;
   
   function Fibonacci_Rec (N : in Positive) return Positive is
   -- Returns the Nth Fibonacci number, computed recursively
   -- Pre : N is defined and N >= 1
   -- Post: returns N!
  
   begin  -- Fibonacci Recursion

      if (N = 1) or (N = 2) then
         return 1;
      else
         return Fibonacci_Rec (N - 2) + Fibonacci_Rec (N - 1);        
      end if;
   end Fibonacci_Rec;

begin -- Test Fibonacci

   Ada.Text_IO.Put (Item => "Please enter an integer (>0) > ");
   Ada.Integer_Text_IO.Get (Item => N);
   Ada.Text_IO.New_Line;
   Ada.Text_IO.Put (Item => "The fibonacci sequence for N ="
                    & Positive'Image (N) & " is: " );
   Ada.Text_IO.New_Line;

   for Count in 1..N loop
      --Ada.Integer_Text_IO.Put (Item => Fibonacci_Iter (N => Count), Width => 1);
      Ada.Integer_Text_IO.Put (Item => Fibonacci_Rec (N => Count), Width => 1);
      Ada.Text_IO.New_Line;
      --Ada.Text_IO.Put(Item => ' ');
   end loop;

   end Test_Fibonacci;

-----------------------------

with Ada.Integer_Text_IO;
with Ada.Text_IO;

procedure Buffer_Overflow is
   Result : Positive;
   N      : Positive;

begin
   Ada.Text_IO.Put (Item => "enter an integer: ");
   Ada.Integer_Text_IO.Get(Item => N);
   Result := N * 2_000_000_000;
   Ada.Integer_Text_IO.Put (Item => Result, Width => 1);
end Buffer_Overflow;


^ permalink raw reply	[relevance 6%]

* Re: OpenSSL development (Heartbleed)
  @ 2014-04-23  8:06  5%                     ` Georg Bauhaus
  0 siblings, 0 replies; 200+ results
From: Georg Bauhaus @ 2014-04-23  8:06 UTC (permalink / raw)


On 23/04/14 09:30, Dmitry A. Kazakov wrote:

>>> Boundary checks or not, the transport layer shall have no access to the
>>> server data.
>>>
>>> A tightly coupled system is vulnerable. If compromising just one component
>>> opens all gates wide, that is a bad standard and bad design. The effects of
>>> errors and faults must be bounded per design.
>>
>> How would you design a transport layer that has no access to whatever is
>> supposed to be transported?
>>
>> "Heartbleed" didn't leak any data that ins't legitimataly needed by
>> OpenSSL (i.e. transported data and/or transport parameters (like keys))
>
> I heard it leaked user data, I didn't go into details. I hope user data are
> not transported, because otherwise that would be even an greater design
> fault.

They are not, by design, transported. I think the issue
boiled down to using some int variable `p' as an offset without
checking bounds. OpenSSL sometimes uses its own malloc,
for historical reasons. So, perhaps this approximates.

At least GNAT warns, no matter what. What do other compiler
diagnose?

with System.Storage_Elements;  use System.Storage_Elements;
with Ada.Integer_Text_IO;

procedure Leak is
    type A is array (Integer range <>) of Storage_Element;
    type A_P is access all A;

    Pool : A (1 .. 123_456);
    for Pool'Address use To_Address (16#100_000#);
    Current_Offset : Storage_Offset := 0;

    function Our_Own_Malloc (Size : Natural) return A_P is
       Result : A_P;
       for Result'Address use Pool'Address + Current_Offset;
    begin
       Current_Offset := Current_Offset + Storage_Offset (Size);
       return Result;
    end Our_Own_Malloc;

    function Something (P : Integer) return A is
       Result : A_P;
    begin
       Result := Our_Own_Malloc (P);
       return Result.all;
    end Something;

    use Ada.Integer_Text_IO;
    I : Integer;
begin
    Get(I);
    declare
       Y : A := Something (I);
    begin
       null;
    end;
end Leak;


^ permalink raw reply	[relevance 5%]

* Re: Problem with generic package
  @ 2014-04-15 21:12  4%   ` Laurent
  0 siblings, 0 replies; 200+ results
From: Laurent @ 2014-04-15 21:12 UTC (permalink / raw)



> so delete the first line and replace Exchange by Swap_Generic in the...

I got that by myself so at least some progress :)

The whole problem comes from the fact that swap_generic and sort_generic where given in the book, the search_generic was left as exercise which I was able to solve.

Just trying to get those 3 things in one package disturbed me. At least I probably won't forget it. 

MacOS doesn't care about case even if it is unix based.

Tried to use my array_generics in some test program. 
error: invalid prefix in selected component "Array_Generics"

the with'ing and prefix'ing is also proposed by gps. perhaps again the same problem as before? not understanding what I am doing? 

Thanks


with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Float_Text_IO;
with Array_Generics;

procedure Test_Search_Array_Generic is

   subtype Index is Integer range 1 .. 10;

   type Float_Vector is array (Index range <>) of Float;

   V1 : Float_Vector (1 .. 10);

 ==>  function Search_Float is new Array_Generics.Search_Generic
     (List_Type => Float_Vector, Index_Type => Index, Element_Type => Float); <== error

   procedure Display_Float_Vector (V : Float_Vector) is

      Target: Float;

   begin -- Display_Float_Vector

      Ada.Text_IO.Put (Item => "Please enter the value to search for: ");
      Ada.Float_Text_IO.Get (Item => Target);
      Ada.Integer_Text_IO.Put (Item => Search_Float (List => V, Target => Target),Width => 1);
      Ada.Text_IO.New_Line;

   exception
      when Array_Generics.Item_Not_Found =>
         Ada.Text_IO.Put (Item => "Target not found!");

   end Display_Float_Vector;

begin

   V1 := (0.7, 1.5, 6.9, -3.2, 0.0, 5.1, 2.0, 7.3, 2.2, -5.9);

   Display_Float_Vector (V => V1);

end Test_Search_Array_Generic;



^ permalink raw reply	[relevance 4%]

* Re: gnatmake error I don't understand
  2014-04-04  0:35  5% gnatmake error I don't understand agent
@ 2014-04-04  4:14  0% ` Per Sandberg
  0 siblings, 0 replies; 200+ results
From: Per Sandberg @ 2014-04-04  4:14 UTC (permalink / raw)


On Thu, 03 Apr 2014 20:35:18 -0400
agent@drrob1.com wrote:
The attribute "Main" is a file-name so it shall be:
   for main use ("habits.adb");
and not:
   for main use ("Habits");
/Per



> I typed the following code from a recent issue of Linux Format
> 
> texthabits.ads
> with Ada.Text_IO, Ada.Strings.Unbounded,
> Ada.Strings.Unbounded.Text_IO, Ada.Integer_Text_IO;
> use  Ada.Text_IO, Ada.Strings.Unbounded,
> Ada.Strings.Unbounded.Text_IO, Ada.Integer_Text_IO;
> 
> -- REVISION HISTORY
> -- ================
> -- 31 Mar 14 -- Extracted from LinuxFormat LXF 181 coding article
> 
> Package texthabits is
> 
> PROCEDURE CreateOrOpen (File: in out File_Type; Name: in String; Form:
> in String := "");
> 
> Procedure OpenOrCreateDataFile(File : in out File_Type; Name : in
> String);
> 
> Procedure ReadAndDisplayDatafile(File : in out File_Type; Name :
> String);
> 
> Procedure Habits ;
> 
> END texthabits;
> 
> -----------------------------------------------------------------------------------------
> texthabits.adb
> with Ada.Text_IO, Ada.Strings.Unbounded,
> Ada.Strings.Unbounded.Text_IO, Ada.Integer_Text_IO, Ada.Calendar,
> Ada.Directories;
> use  Ada.Text_IO, Ada.Strings.Unbounded,
> Ada.Strings.Unbounded.Text_IO, Ada.Integer_Text_IO, Ada.Calendar,
> Ada.Directories;
> 
> -- REVISION HISTORY
> -- ================
> -- 31 Mar 14 -- Extracted from LinuxFormat LXF 181 coding article
> 
> 
> Package body texthabits is
>   habit : Unbounded_String;
>   filehandle : File_Type;
>   HabitFileName : String(1..13);
>   ctr : Natural := 1;
> 
> PROCEDURE CreateOrOpen (File: in out File_Type; Name: in String; Form:
> in String := "") is
> BEGIN
>   Open(File, Append_File, Name, Form);
> EXCEPTION
>   WHEN Ada.Text_IO.Name_Error =>
>     Create(File, Out_File, Name, Form);  -- If must create file, then
> append_file does not make sense, even if desired.
> END CreateOrOpen;
> 
> Procedure OpenOrCreateDataFile(File : in out File_Type; Name : in
> String) is
> Begin
>   Open(File, Append_File, Name);
> Exception
>   when Ada.Text_IO.Name_Error => Create(File => File, Mode =>
> Append_File, Name => Name);
> End OpenOrCreateDataFile;
> 
> Procedure ReadAndDisplayDatafile(File : in out File_Type; Name :
> String) is
>   buffer : String(1..100);
>   length : Natural;
> Begin
>   IF EXISTS(Name) THEN
>     Open(File => File, Mode => In_File, Name => Name);
>     While not End_Of_File(File => File) loop
>       Get_Line(File => File, item => buffer, last => Length);
>       Put_Line(buffer(1..length));
>     end loop;
>     Close(File);
>   END IF; -- if exists 
> End ReadAndDisplayDatafile;
> 
> 
> Procedure Habits is
> Begin
>   HabitFileName  :=  "habitfile.txt";
>   ReadAndDisplayDatafile(filehandle, HabitFileName);  -- for input. Do
> nothing if file does not exist.
>   OpenOrCreateDataFile(filehandle, HabitFileName);    -- for output
>   LOOP
>     Put(" Enter a new habit, quit or exit: ");
>     habit  :=  Get_Line;
>     exit when (CAP(To_STRING(Head(Habit,4))) = "QUIT") OR
> (CAP(to_string(Head(Habit,4))) = "EXIT") ;
>     Put_Line(filehandle,Habit);
>     ctr := ctr + 1;
>   END LOOP;
>   Close(filehandle);
>   Put(" You entered and saved ");
>   Put(ctr,3);
>   Put_Line(" new habits.");
> End Habits;
> 
> END texthabits;
> ---------------------------------------------------------------------------------
> texthabits.gpr
> project texthabits is
>   for Source_Files use ("texthabits.adb", "texthabits.ads",
> "tokenizea.ads", "tokenizea.adb");
>   for Source_Dirs use (".", "./**");
>   for Main use ("Habits");                                            
> 
>   package Builder is
>     for Default_Switches ("Ada")
>         use ("-g");
>   end Builder;
> 
>   package Compiler is
>     for Default_Switches ("Ada")
>        use ("-fstack-check",
>             "-gnatVa",
>             "-g",
>             "-gnato",
>             "-gnatf",
>             "-gnatwu",
>             "-gnat2012");
>   end Compiler;
>    
> end texthabits;
> 
> ------------------------------------------------------------------------------
> Ubuntu 12.04  amd64 version
> 
> gnatmake -Ptexthabits
> 
> gnatmake: "Habits" is not a source of project texthabits.
> 
> I don't understand the error or what to do about it.
> 
> Thanks,
> Rob Solomon
> 


^ permalink raw reply	[relevance 0%]

* gnatmake error I don't understand
@ 2014-04-04  0:35  5% agent
  2014-04-04  4:14  0% ` Per Sandberg
  0 siblings, 1 reply; 200+ results
From: agent @ 2014-04-04  0:35 UTC (permalink / raw)


I typed the following code from a recent issue of Linux Format

texthabits.ads
with Ada.Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO, Ada.Integer_Text_IO;
use  Ada.Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO, Ada.Integer_Text_IO;

-- REVISION HISTORY
-- ================
-- 31 Mar 14 -- Extracted from LinuxFormat LXF 181 coding article

Package texthabits is

PROCEDURE CreateOrOpen (File: in out File_Type; Name: in String; Form:
in String := "");

Procedure OpenOrCreateDataFile(File : in out File_Type; Name : in
String);

Procedure ReadAndDisplayDatafile(File : in out File_Type; Name :
String);

Procedure Habits ;

END texthabits;

-----------------------------------------------------------------------------------------
texthabits.adb
with Ada.Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO, Ada.Integer_Text_IO, Ada.Calendar,
Ada.Directories;
use  Ada.Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO, Ada.Integer_Text_IO, Ada.Calendar,
Ada.Directories;

-- REVISION HISTORY
-- ================
-- 31 Mar 14 -- Extracted from LinuxFormat LXF 181 coding article


Package body texthabits is
  habit : Unbounded_String;
  filehandle : File_Type;
  HabitFileName : String(1..13);
  ctr : Natural := 1;

PROCEDURE CreateOrOpen (File: in out File_Type; Name: in String; Form:
in String := "") is
BEGIN
  Open(File, Append_File, Name, Form);
EXCEPTION
  WHEN Ada.Text_IO.Name_Error =>
    Create(File, Out_File, Name, Form);  -- If must create file, then
append_file does not make sense, even if desired.
END CreateOrOpen;

Procedure OpenOrCreateDataFile(File : in out File_Type; Name : in
String) is
Begin
  Open(File, Append_File, Name);
Exception
  when Ada.Text_IO.Name_Error => Create(File => File, Mode =>
Append_File, Name => Name);
End OpenOrCreateDataFile;

Procedure ReadAndDisplayDatafile(File : in out File_Type; Name :
String) is
  buffer : String(1..100);
  length : Natural;
Begin
  IF EXISTS(Name) THEN
    Open(File => File, Mode => In_File, Name => Name);
    While not End_Of_File(File => File) loop
      Get_Line(File => File, item => buffer, last => Length);
      Put_Line(buffer(1..length));
    end loop;
    Close(File);
  END IF; -- if exists 
End ReadAndDisplayDatafile;


Procedure Habits is
Begin
  HabitFileName  :=  "habitfile.txt";
  ReadAndDisplayDatafile(filehandle, HabitFileName);  -- for input. Do
nothing if file does not exist.
  OpenOrCreateDataFile(filehandle, HabitFileName);    -- for output
  LOOP
    Put(" Enter a new habit, quit or exit: ");
    habit  :=  Get_Line;
    exit when (CAP(To_STRING(Head(Habit,4))) = "QUIT") OR
(CAP(to_string(Head(Habit,4))) = "EXIT") ;
    Put_Line(filehandle,Habit);
    ctr := ctr + 1;
  END LOOP;
  Close(filehandle);
  Put(" You entered and saved ");
  Put(ctr,3);
  Put_Line(" new habits.");
End Habits;

END texthabits;
---------------------------------------------------------------------------------
texthabits.gpr
project texthabits is
  for Source_Files use ("texthabits.adb", "texthabits.ads",
"tokenizea.ads", "tokenizea.adb");
  for Source_Dirs use (".", "./**");
  for Main use ("Habits");                                            

  package Builder is
    for Default_Switches ("Ada")
        use ("-g");
  end Builder;

  package Compiler is
    for Default_Switches ("Ada")
       use ("-fstack-check",
            "-gnatVa",
            "-g",
            "-gnato",
            "-gnatf",
            "-gnatwu",
            "-gnat2012");
  end Compiler;
   
end texthabits;

------------------------------------------------------------------------------
Ubuntu 12.04  amd64 version

gnatmake -Ptexthabits

gnatmake: "Habits" is not a source of project texthabits.

I don't understand the error or what to do about it.

Thanks,
Rob Solomon



^ permalink raw reply	[relevance 5%]

* Re: Reading data from file
  2014-03-05 21:13  5%           ` Laurent
@ 2014-03-05 21:25  0%             ` Niklas Holsti
  0 siblings, 0 replies; 200+ results
From: Niklas Holsti @ 2014-03-05 21:25 UTC (permalink / raw)


On 14-03-05 23:13 , Laurent wrote:
> It is this what he meant?
> 
> Ada.Integer_Text_IO.Get (File => Import_File, Item => Temp_Record.ID);
> Ada.Text_IO.Skip_Line;
> Ada.Text_IO.Get_Line(File => Import_File, Item => Temp_Record.Name,Last => Name_Length);
> 
> That doesn't work.

You have to do

   Ada.Text_IO.Skip_Line (Import_File);

Just Skip_Line with no parameters skips a line on Standard_Input, which
is not what you want.

I'm sorry if my suggestion was unclear.

-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
      .      @       .


^ permalink raw reply	[relevance 0%]

* Re: Reading data from file
  @ 2014-03-05 21:13  5%           ` Laurent
  2014-03-05 21:25  0%             ` Niklas Holsti
  0 siblings, 1 reply; 200+ results
From: Laurent @ 2014-03-05 21:13 UTC (permalink / raw)


It is this what he meant?

Ada.Integer_Text_IO.Get (File => Import_File, Item => Temp_Record.ID);
Ada.Text_IO.Skip_Line;
Ada.Text_IO.Get_Line(File => Import_File, Item => Temp_Record.Name,Last => Name_Length);

That doesn't work.

Ada.Integer_Text_IO.Get (File => Import_File, Item => Temp_Record.ID);
Ada.Text_IO.Skip_Line;
Ada.Text_IO.Get(File => Import_File, Item => Temp_Record.Name);

Works (not forgetting to add the spaces in the txt file)

> The Skip_Line works only if I use it together with: 
> Ada.Text_IO.Get (File => Import_File, Item => Temp_Record.Name); 

Hm yes quit confuse sentence. I knew what I meant to say which doesn't
imply that that someone else does. Sry



^ permalink raw reply	[relevance 5%]

* Re: Reading data from file
  2014-03-04 21:27  4%   ` Laurent
@ 2014-03-04 21:42  0%     ` Niklas Holsti
    1 sibling, 0 replies; 200+ results
From: Niklas Holsti @ 2014-03-04 21:42 UTC (permalink / raw)


On 14-03-04 23:27 , Laurent wrote:
> Hi
> 
> @Mike: Thanks for this detailed example. 
> 
> Unfortunately I seem to have mixed up a few things while writing my post. 
> 
> The text file contains just:
>    
>   1234
>   test
>   male ...
> 
> The ID: ,... was just supposed to inform you about the type. 
> 
> The exact error message is: 
> 
> raised ADA.IO_EXCEPTIONS.DATA_ERROR : a-tienio.adb:57 instantiated at employees-io.adb:17
> 
> which is:
> 
>     type GenderType is (Female, Male);     
> 
>      package GenderType_IO is
>      new Ada.Text_IO.Enumeration_IO (Enum => GenderType);
> 
> Here is my code. It compiles but it isn't complete. Will
> probably fail for the moment if I try to read more than
> one record. (Won't read even one so...). Reading the name
> could be one reason for the problem with the enumeration.

I believe you have found the error there...

> procedure Read_Employee_From_File (Item : out Employees.Employee) is
> 
>       Import_File : Ada.Text_IO.File_Type;
>       Temp_Record : Employees.Employee;
>       Name_Length: Natural;
> 
>    begin -- Read_Employee_From_File
> 
>       -- open the file and associate it with the file variable name
>       Ada.Text_IO.Open (File => Import_File, Mode => Ada.Text_IO.In_File,
>                                    Name => "Datafile.txt");
> 
>       -- read each data item
> 
>       loop
>          exit when Ada.Text_IO.End_Of_File (Import_File);
> 
>          Ada.Integer_Text_IO.Get (File => Import_File, Item => Temp_Record.ID);

The above Get will leave the file read pointer at the point after the
last digit of the ID number, which is at the end-of-line marker for that
line.

>          Ada.Text_IO.Get_Line (File => Import_File, Item => Temp_Record.Name, Last => Name_Length);

The above Get_Line will then read the rest of the ID line, up to the
end-of-line marker, and the result is the empty string (unless there is
something after the ID and before the end of the line).

The file read point is left at the start of the "name" line.

>          GenderType_IO.Get (File => Import_File, Item => Temp_Record.Gender);

That tries to the string "test" as a GenderType, causing the failure.

So the problem is that after reading the ID you must move the read point
to the start of the "name" line. Add a Skip_Line between the Get(ID) and
the Get_Line(Name).

> PS: Will never again post a message from my smartphone. crap onscreen keyboard/tiny screen. Not made for browsing a forum.

Also try to configure your news-reader to break the lines in your
postings to some reasonable length, say 70 characters. Commenting is
difficult if you post messages with very long lines, at least in my
news-reader (Thunderbird).

-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
      .      @       .

^ permalink raw reply	[relevance 0%]

* Re: Reading data from file
  @ 2014-03-04 21:27  4%   ` Laurent
  2014-03-04 21:42  0%     ` Niklas Holsti
    0 siblings, 2 replies; 200+ results
From: Laurent @ 2014-03-04 21:27 UTC (permalink / raw)


Hi

@Mike: Thanks for this detailed example. 

Unfortunately I seem to have mixed up a few things while writing my post. 

The text file contains just:
   
  1234
  test
  male ...

The ID: ,... was just supposed to inform you about the type. 

The exact error message is: 

raised ADA.IO_EXCEPTIONS.DATA_ERROR : a-tienio.adb:57 instantiated at employees-io.adb:17

which is:

    type GenderType is (Female, Male);     

     package GenderType_IO is
     new Ada.Text_IO.Enumeration_IO (Enum => GenderType);

Here is my code. It compiles but it isn't complete. Will probably fail for the moment if I try to read more than one record. (Won't read even one so...). Reading the name could be one reason for the problem with the enumeration. 

procedure Read_Employee_From_File (Item : out Employees.Employee) is

      Import_File : Ada.Text_IO.File_Type;
      Temp_Record : Employees.Employee;
      Name_Length: Natural;

   begin -- Read_Employee_From_File

      -- open the file and associate it with the file variable name
      Ada.Text_IO.Open (File => Import_File, Mode => Ada.Text_IO.In_File,
                                   Name => "Datafile.txt");

      -- read each data item

      loop
         exit when Ada.Text_IO.End_Of_File (Import_File);

         Ada.Integer_Text_IO.Get (File => Import_File, Item => Temp_Record.ID);
         Ada.Text_IO.Get_Line (File => Import_File, Item => Temp_Record.Name, Last => Name_Length);
         GenderType_IO.Get (File => Import_File, Item => Temp_Record.Gender);
         Ada.Integer_Text_IO.Get (File => Import_File, Item => Temp_Record.NumDepend);
         Currency.IO.Get (File => Import_File, Item => Temp_Record.Salary);
         Dates.IO.Get (File => Import_File, Item => Temp_Record.StartDate);

         Item := Temp_Record;

      end loop;


   end Read_Employee_From_File;

There is an other exercise in the book which uses this construction too and which works. Just reads a string and an int  until the end of the file. 

@Adam: I think I have to put a line to display what my construction is reading/and the content of Temp_Record just before the program terminates.


Other question: I have a working procedure to get the same information but from terminal which also checks if the data is correctly formatted. Is it possible to reroute the info from the file to this procedure? If yes how would I do that.

Because I (rather the author of the book) have this procedures which seem to do the same thing (or the other way around. Don't really understand why there are 2 procedures for the same thing).  Just that until now I didn't read anything from a file.


procedure Get (File : in Ada.Text_IO.File_Type; Item : out Quantity) is
      F : Float;
   begin -- get

      -- just read it as a float quantity, then convert
      Ada.Float_Text_IO.Get (File => File, Item => F);
      Item := MakeCurrency (F);

   end Get;

 procedure Get (Item : out Quantity) is
   begin -- get
      Get (File => Ada.Text_IO.Standard_Input, Item => Item);
   end Get;

Thanks

Laurent

PS: Will never again post a message from my smartphone. crap onscreen keyboard/tiny screen. Not made for browsing a forum.

^ permalink raw reply	[relevance 4%]

* Re: Something I don't understand
  2014-02-15 19:10  4%     ` Laurent
  2014-02-15 20:05  0%       ` Niklas Holsti
@ 2014-02-16  1:39  0%       ` Robert A Duff
  1 sibling, 0 replies; 200+ results
From: Robert A Duff @ 2014-02-16  1:39 UTC (permalink / raw)


Laurent <daemon2@internet.lu> writes:

> Now it works as I think it should.

Good.

FWIW, Text_IO is a poor design, and I don't blame you for having
trouble with it!

Some stylistic comments on the code below:

Exceptions are for dealing with cases where one piece of code detects
a (possible) error, and another piece of code decides whether it
really is an error, and how to deal with it.  That's not the
case here, so should be written without any exceptions.

No need for a loop name.

You should use typical style, so other Ada programmers can read your
code more easily:  lower case keywords, Max_Name instead of MaxName.
(Or Max_Name_Length?)  Space after "--".

S should declared "constant".  You should enable warnings in GNAT
that detect this mistake.

Why should there be a limit on the length of the name?  Maybe you have
a good reason, but usually such arbitrary limits are a bad idea.

> Name : LOOP            
>             BEGIN --exception handler block
>                Ada.Text_IO.Put ("Name (1 - ");                  
>                Ada.Integer_Text_IO.Put (Item => MaxName, Width => 1);
>                Ada.Text_IO.Put (Item => " characters) >"); 
>                
>                DECLARE
>                   S : String := Ada.Text_IO.Get_Line;
>                
>                BEGIN
>                   IF S'Length = 0 THEN
>                      RAISE Name_Too_Short;
>                   ELSIF S'Length <= MaxName THEN
>                      Item.Name (1 .. S'Length) := S;                     
>                   ELSE RAISE Name_Too_Long;   
>                   END IF;
>                   
>                   EXIT; -- correct Name                  
>
>                EXCEPTION
>                      
>                   WHEN Name_Too_Short =>                     
>                      Ada.Text_IO.Skip_Line;
>                      Ada.Text_IO.Put (Item => "Name too short!");                     
>                      Ada.Text_IO.New_Line;                     
>                   WHEN Name_Too_Long =>                     
>                      Ada.Text_IO.Skip_Line;                     
>                      Ada.Text_IO.Put_Line (Item => "Name too long!");                     
>
>                END; -- exception handler
>             END;
>          END LOOP Name;

^ permalink raw reply	[relevance 0%]

* Re: Something I don't understand
  2014-02-15 19:10  4%     ` Laurent
@ 2014-02-15 20:05  0%       ` Niklas Holsti
  2014-02-16  1:39  0%       ` Robert A Duff
  1 sibling, 0 replies; 200+ results
From: Niklas Holsti @ 2014-02-15 20:05 UTC (permalink / raw)


On 14-02-15 21:10 , Laurent wrote:
> Hi
> 
> Now it works as I think it should.
> 
> Name : LOOP            
>             BEGIN --exception handler block
>                Ada.Text_IO.Put ("Name (1 - ");                  
>                Ada.Integer_Text_IO.Put (Item => MaxName, Width => 1);
>                Ada.Text_IO.Put (Item => " characters) >"); 

You might want to insert Ada.Text_IO.Flush here, to make sure that the
preceding Put text appears on the terminal. (I'm not sure if the
standard requires an implicit Flush when a Put is followed by a Get.)

>                DECLARE
>                   S : String := Ada.Text_IO.Get_Line;
    [snip]
>                EXCEPTION
>                      
>                   WHEN Name_Too_Short =>                     
>                      Ada.Text_IO.Skip_Line;
    [snip]

> The only thing which I find annoying is the fact that I
> have to tape ENTER 2 times.

Does that happen only in the exception cases? Then the reason is
probably the Skip_Line calls in the exception handlers. They are
superfluous because the Get_Line function includes the effect of a
Skip_Line (RM 17.2/2) -- it consumes the line terminator. Remove the
Skip_Lines.

-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
      .      @       .


^ permalink raw reply	[relevance 0%]

* Re: Something I don't understand
  @ 2014-02-15 19:10  4%     ` Laurent
  2014-02-15 20:05  0%       ` Niklas Holsti
  2014-02-16  1:39  0%       ` Robert A Duff
  0 siblings, 2 replies; 200+ results
From: Laurent @ 2014-02-15 19:10 UTC (permalink / raw)


Hi

Now it works as I think it should.

Name : LOOP            
            BEGIN --exception handler block
               Ada.Text_IO.Put ("Name (1 - ");                  
               Ada.Integer_Text_IO.Put (Item => MaxName, Width => 1);
               Ada.Text_IO.Put (Item => " characters) >"); 
               
               DECLARE
                  S : String := Ada.Text_IO.Get_Line;
               
               BEGIN
                  IF S'Length = 0 THEN
                     RAISE Name_Too_Short;
                  ELSIF S'Length <= MaxName THEN
                     Item.Name (1 .. S'Length) := S;                     
                  ELSE RAISE Name_Too_Long;   
                  END IF;
                  
                  EXIT; -- correct Name                  

               EXCEPTION
                     
                  WHEN Name_Too_Short =>                     
                     Ada.Text_IO.Skip_Line;
                     Ada.Text_IO.Put (Item => "Name too short!");                     
                     Ada.Text_IO.New_Line;                     
                  WHEN Name_Too_Long =>                     
                     Ada.Text_IO.Skip_Line;                     
                     Ada.Text_IO.Put_Line (Item => "Name too long!");                     

               END; -- exception handler
            END;
         END LOOP Name;

The only thing which I find annoying is the fact that I have to tape ENTER 2 times.

@Adam: Thanks for your example

Thanks

Laurent 


^ permalink raw reply	[relevance 4%]

* Re: Something I don't understand
  2014-02-14  0:18  0% ` adambeneschan
@ 2014-02-14  7:05  0%   ` Charles H. Sampson
    1 sibling, 0 replies; 200+ results
From: Charles H. Sampson @ 2014-02-14  7:05 UTC (permalink / raw)


<adambeneschan@gmail.com> wrote:

> On Thursday, February 13, 2014 3:57:58 PM UTC-8, Laurent wrote:
> > Hi
> > 
> > 
> > 
> > Doing an exercise from the book "Ada 95 Problem Solving and Program Design".
> > 
> > I am supposed to make a robust function to read some values. It works so
> > far but there is one thing I don't understand.
>  
> >    MaxName : CONSTANT Positive := 30; -- defined in other package 
> >    SUBTYPE NameType IS String (1 .. MaxName); -- defined in other package
> > 
> >    Count : Natural RANGE 1.. MaxName;
> >
> >          Name : LOOP
> >                BEGIN --exception handler block               
> >                     Ada.Text_IO.Put ("Name (1 - ");
> >                     Ada.Integer_Text_IO.Put (Item => MaxName,Width => 1);
> >                     Ada.Text_IO.Put(Item => " characters) >");
> >                     Ada.Text_IO.Get_Line (Item => S, Last => Count);
> >                     Item.Name (1 .. Count) := S (1 .. Count);  
> >                     Ada.Text_IO.Skip_Line;
> > 
> >                EXIT; -- correct Name
> > 
> >             EXCEPTION
> >                WHEN Constraint_Error =>
> >                   Ada.Text_IO.Skip_Line;
> >                   Ada.Text_IO.Put (Item => "Name too short/long!");
> >                   Ada.Text_IO.New_Line;
> > 
> >             END; -- exception handler
> > 
> >          END LOOP Name;
> > 
> > 
> > 
> > 
> > 
> > So when I enter nothing as name I get a Constraint_Error which is
> > handled. That's ok but when the name I enter is longer than 30 chars no
> > exception. Is that normal and if yes/no why?
> 
> Yes, because that's how the *procedure* Get_Line is defined.  It stops
> reading when it reaches the end of the string, or the end of the line.
> (RM A.10.7(18-20))
> 
> If you want to check for input that is too long, you can use the
> *function* Get_Line, which always reads to the end of the line:
> 
>     declare
>         Input : String := Ada.Text_IO.Get_Line;
>     begin
>         if Input'Length <= NameType'Length then
>             Item.Name (1 .. Input'Length) := Input;
>             --Ada.Text_IO.Skip_Line;  --you shouldn't need this, Get_Line will
>                                       --automatically perform this
>             exit Name;  -- correct name
>         else
>             Ada.Text_IO.Put_Line (Item => "Name too long!");
>             -- combination of Put and New_Line
>         end if;
>     end;  -- this ends the block starting with "declare"

     It should be mentioned that in the OP's version the extra
characters aren't discarded. They're still there to be "gotten" on the
next use of Get or Get_Line. As Mr. Beneschan hinted in his comment
above, if you want to get rid of them you need to call Skip_Line.

     Just another example of Ada not doing things behind the scene.

                        Charlie
-- 
Nobody in this country got rich on his own.  You built a factory--good.
But you moved your goods on roads we all paid for.  You hired workers we
all paid to educate. So keep a big hunk of the money from your factory.
But take a hunk and pay it forward.  Elizabeth Warren (paraphrased)


^ permalink raw reply	[relevance 0%]

* Re: Something I don't understand
  2014-02-13 23:57  3% Something I don't understand Laurent
@ 2014-02-14  0:18  0% ` adambeneschan
  2014-02-14  7:05  0%   ` Charles H. Sampson
    0 siblings, 2 replies; 200+ results
From: adambeneschan @ 2014-02-14  0:18 UTC (permalink / raw)


On Thursday, February 13, 2014 3:57:58 PM UTC-8, Laurent wrote:
> Hi
> 
> 
> 
> Doing an exercise from the book "Ada 95 Problem Solving and Program Design".
> 
> I am supposed to make a robust function to read some values. It works so far but there is one thing I don't
> 
> understand.
 
>    MaxName : CONSTANT Positive := 30; -- defined in other package 
>    SUBTYPE NameType IS String (1 .. MaxName); -- defined in other package
> 
>    Count : Natural RANGE 1.. MaxName;
>
>          Name : LOOP
>                BEGIN --exception handler block               
>                     Ada.Text_IO.Put ("Name (1 - ");
>                     Ada.Integer_Text_IO.Put (Item => MaxName,Width => 1);
>                     Ada.Text_IO.Put(Item => " characters) >");
>                     Ada.Text_IO.Get_Line (Item => S, Last => Count);
>                     Item.Name (1 .. Count) := S (1 .. Count);  
>                     Ada.Text_IO.Skip_Line;
> 
>                EXIT; -- correct Name
> 
>             EXCEPTION
>                WHEN Constraint_Error =>
>                   Ada.Text_IO.Skip_Line;
>                   Ada.Text_IO.Put (Item => "Name too short/long!");
>                   Ada.Text_IO.New_Line;
> 
>             END; -- exception handler
> 
>          END LOOP Name;
> 
> 
> 
> 
> 
> So when I enter nothing as name I get a Constraint_Error which is handled. That's ok but when the name I enter is longer than 30 chars no exception. Is that normal and if yes/no why? 

Yes, because that's how the *procedure* Get_Line is defined.  It stops reading when it reaches the end of the string, or the end of the line.  (RM A.10.7(18-20))

If you want to check for input that is too long, you can use the *function* Get_Line, which always reads to the end of the line:

    declare
        Input : String := Ada.Text_IO.Get_Line;
    begin
        if Input'Length <= NameType'Length then
            Item.Name (1 .. Input'Length) := Input;
            --Ada.Text_IO.Skip_Line;  --you shouldn't need this, Get_Line will
                                      --automatically perform this
            exit Name;  -- correct name
        else
            Ada.Text_IO.Put_Line (Item => "Name too long!");
            -- combination of Put and New_Line
        end if;
    end;  -- this ends the block starting with "declare"

                            -- Adam

^ permalink raw reply	[relevance 0%]

* Something I don't understand
@ 2014-02-13 23:57  3% Laurent
  2014-02-14  0:18  0% ` adambeneschan
  0 siblings, 1 reply; 200+ results
From: Laurent @ 2014-02-13 23:57 UTC (permalink / raw)


Hi

Doing an exercise from the book "Ada 95 Problem Solving and Program Design".
I am supposed to make a robust function to read some values. It works so far but there is one thing I don't
understand.

   MaxName : CONSTANT Positive := 30; -- defined in other package
   SUBTYPE NameType IS String (1 .. MaxName); -- defined in other package

   Count : Natural RANGE 1.. MaxName;

         Name : LOOP
               BEGIN --exception handler block               
                    Ada.Text_IO.Put ("Name (1 - ");
                    Ada.Integer_Text_IO.Put (Item => MaxName,Width => 1);
                    Ada.Text_IO.Put(Item => " characters) >");
                    Ada.Text_IO.Get_Line (Item => S, Last => Count);
                    Item.Name (1 .. Count) := S (1 .. Count);  
                    Ada.Text_IO.Skip_Line;
            
               EXIT; -- correct Name
               
            EXCEPTION
               WHEN Constraint_Error =>
                  Ada.Text_IO.Skip_Line;
                  Ada.Text_IO.Put (Item => "Name too short/long!");
                  Ada.Text_IO.New_Line;
                  
            END; -- exception handler
         END LOOP Name;


So when I enter nothing as name I get a Constraint_Error which is handled. That's ok but when the name I enter is longer than 30 chars no exception. Is that normal and if yes/no why? 

The chars that are to much are just ignored.

Thanks

Laurent


^ permalink raw reply	[relevance 3%]

* need help learning Ada for a modula-2 programmer
@ 2014-01-28  1:06  3% agent
  0 siblings, 0 replies; 200+ results
From: agent @ 2014-01-28  1:06 UTC (permalink / raw)


The following code does not compile.  I don't understand why.

The string processing fails to compile, saying "prefix of image must
be a type"

and 

"move is undefined"

I don't yet understand string processing with Ada

--rob

with Ada.Calendar; use Ada.Calendar;
Package timliba is

--  REVISION HISTORY
--  ----------------
--   6 Oct 13 -- Converted to gm2.  And changed its name.
--  19 Jan 14 -- Converted to Ada.

  SubType String10Type is String(1..10);
  TYPE DAYNAMESType is ARRAY (1..7) OF String10Type;
  TYPE MONTHNAMESType is ARRAY (1..12) OF String10Type;
  Type DateTimeType is RECORD
    SystemTime: Time;
    month,day,year,hours,minutes,seconds : Natural;
    ElapsedSec : Duration;
  END Record;

  DateTime: DateTimeType;

  DAYNAMES : Constant DayNamesType  := ("Sunday    ","Monday
","Tuesday   ","Wednesday ", "Thursday  ","Friday    ","Saturday  ");
  MONTHNAMES : Constant MonthNamesType := ("January   ","February
","March     ","April     ","May       ",
      "June      ","July      ","August    ","September ","October
","November  ","December  ");

PROCEDURE TIME2MDY(M,D,Y : Out Natural);
-- System Time To Month, Day, and Year Conversion.

Procedure GetDateTime(DateTime: Out DateTimeType);
-- DateTimeType is my record time type containing everything.

Function JULIAN(M,D,Y : Natural) return Natural;

PROCEDURE GREGORIAN(Juldate : Natural; M,D,Y : OUT Natural);

END timliba;



-- with environa; use environa;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Characters; use Ada.Characters;
with Ada.Characters.Conversions;  use Ada.Characters.Conversions;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Calendar; use Ada.Calendar;

Package body timliba is

--  REVISION HISTORY
--  ----------------
--  14 Apr 92 -- Created JULIAN and GREGORIAN procs, which are
accurate beyond 3/1/2100.
--  25 Jul 93 -- Changed GREG2JUL and JUL2GREG limits to those imposed
by the
--                algorithm, ie, only years <2100 are now allowed.
--  25 Jul 94 -- Changed limits of allowed years to 1700 from 1900.
--  10 Nov 02 -- Converted to SBM2 Win v4.
--  17 May 03 -- First Win32 version.
--  26 May 03 -- Adjusted algorithm for Julian fcn so year has a
pivot.
--   6 Oct 13 -- Converted to gm2.
--  19 Jan 14 -- Converted to Ada.

  SubType String255 is String(1..255);
  K,IDX,PTR,c,RETCOD                           : Natural;
  CH                                           : CHARacter;
  FLAG,FLAG2,FLAG3,FLAG4,FLAG5,EOFFLG          : BOOLEAN;
--  PROMPT,NAMDFT,TYPDFT,INFNAM,OUTFNAM,
--  TMPBUF,NUMBUF,DRVPATH,INBUF,TOKEN            : BUFTYP;
--  TKNSTATE                                     : FSATYP;
  I,J                                          : INTEGER;

  TYPE ADIPMType is ARRAY (0..11) OF INTEGER;

--  This is a typed constant that represents the difference btwn the
last day
--  of the previous month and 30, assuming each month was 30 days
long.
--  The variable name is an acronym of Accumulated Days In Previous
Months.

  ADIPM : CONSTant ADIPMType :=  (0,1,-1,0,0,1,1,2,3,3,4,4);
  FUDGEFACTOR : CONSTant LONG_FLOAT := 5.0;
-- These are declared in the spec file
--  Type DateTimeType is RECORD
--    SystemTime: Time;
--    month,day,year,hours,minutes,seconds : Natural;
--    ElapsedSec : Duration;
--  END Record;


PROCEDURE TIME2MDY(M,D,Y : Out Natural) is
-- *********************************** TIME2MDY
*************************
-- System Time To Month, Day, and Year Conversion.

  Systime : Time;

BEGIN
  Systime := Clock;
  M := Month(Systime);
  D := Day(Systime);
  Y := Year(Systime);
END TIME2MDY;

Procedure GetDateTime(DateTime : Out DateTimeType) is
   CardSec : Natural;

BEGIN
  DateTime.SystemTime := Clock;

Split(DateTime.SystemTime,DateTime.year,DateTime.month,DateTime.day,DateTime.ElapsedSec);
  CardSec := Natural(DateTime.ElapsedSec+0.5);
  DateTime.hours := CardSec / 3600;
  CardSec := CardSec - DateTime.hours * 3600;
  DateTime.minutes := CardSec / 60;
  DateTime.seconds := CardSec MOD 60;
END GetDateTime;


PROCEDURE MDY2STR(M,D,Y : Natural; MDYSTR : Out String255) is
-- ***************************** MDY2STR
*********************************
-- Month Day Year Cardinals To String.

  DateSepChar : constant character :=  '/';
  MSTR,DSTR,YSTR : String(1..2);
  IntermedStr    : String(1..10);
  m0,d0,y0       : Natural;

BEGIN
  m0 := M;
  d0 := D;
  y0 := Y;
  IntermedStr := m0'Image & DateSepChar & d0'Image & DateSepChar &
y0'Image;
--  DSTR := D'Image;
--  YSTR := Y'Image;
--  MDYSTR := To255(IntermedStr);
    Move(IntermedStr,MDYstr);
END MDY2STR;



Function JULIAN(M,D,Y : Natural) return Natural is

  M0,D0,Y0   : Natural;
  Juldate    : Natural;

BEGIN
  IF Y < 30 THEN
    Y0 := Y + 2000 - 1;
  ELSIF Y < 100 THEN
    Y0 := Y + 1900 - 1;
  ELSE
    Y0 := Y - 1;
  END IF;
  IF (M < 1) OR (M > 12) OR (D < 1) OR (D > 31) OR (Y < 1700) OR (Y >
2500) THEN
-- Month, Day or Year is out of range
    Juldate := 0;
    RETURN(Juldate);
  END IF;

  M0 := M - 1;

  Juldate :=  Y0 * 365     -- Number of days in previous normal years
            + Y0 / 4   -- Number of possible leap days
            - Y0 / 100 -- Subtract all century years
            + Y0 / 400 -- Add back the true leap century years
            + ADIPM(M0) + M0 * 30 + D;

  IF ((( Y MOD 4 = 0) AND ( Y MOD 100 /= 0)) OR ( Y MOD 400 = 0)) AND
--   123            3     3               32    2              21
                                                                 (M >
2) THEN
    Juldate := Juldate + 1;
  END IF;
  RETURN Juldate;
END JULIAN;

PROCEDURE GREGORIAN(Juldate : Natural; M,D,Y : OUT Natural) is

  Y0,M0,D0,L,JD : Natural;

BEGIN
  Y0 := Juldate / 365;
  M0 := 1;
  D0 := 1;

  WHILE JULIAN(M0,D0,Y0) > Juldate LOOP Y0 := Y0 - 1; END Loop;

  M0 := 12;
  WHILE JULIAN(M0,D0,Y0) > Juldate Loop M0 := M0 - 1; END Loop;

  WHILE JULIAN(M0,D0,Y0) < Juldate Loop D0 := D0 + 1; END Loop;

  M := M0;
  D := D0;
  Y := Y0;
END GREGORIAN;

END timliba;


^ permalink raw reply	[relevance 3%]

* Re: Will Ada-95 Programs Written in MS Windows Run in MacOS and Linux Without Some Tweaking.
  2013-12-10 21:49  0%               ` Randy Brukardt
@ 2013-12-11 10:35  3%                 ` Austin Obyrne
  0 siblings, 0 replies; 200+ results
From: Austin Obyrne @ 2013-12-11 10:35 UTC (permalink / raw)


On Tuesday, December 10, 2013 9:49:36 PM UTC, Randy Brukardt wrote: > "Austin Obyrne" <austin.obyrne@hotmail.com> wrote in message news:2b6dc37f-4aa6-4c18-be59-8c09f6f37f01@googlegroups.com... On Tuesday, December 10, 2013 6:37:28 AM UTC, Randy Brukardt wrote: ... >Please consider this procedure in the program that gave trouble, > >This is the defacto stripped down procedure > >EXIT when EOF; > EXIT when EOL; > > FOR I IN 1 .. 3 LOOP > Ada.Integer_Text_IO.Get(File => InData, Item => W(I)); > --Ada.Integer_Text_IO.Put(Item => W(I), Width => 8); > END LOOP; > >LOOP; >LOOP; I presume that there is a New_Line in there somewhere so that the line endings aren't lost completely. But this isn't going to work, as Get for a character is defined as follows: "After skipping any line terminators and any page terminators, reads the next character from the specified input file and returns the value of this character in the out parameter Item." So if you have any line endings in between the 1st and 2nd characters (or between the 2nd and 3rd characters), you'll end up ignoring them. I doubt that's what you want. (Ada abstracts the line, page, and file terminators so you don't have to worry about how they're represented. The problem being that you *can't* see how they're represented if you are using Text_IO.) Using Text_IO without losing line endings and the like is tricky. I generally don't bother, just reading a line at a time with Get_Line and then process whatever I get. (And I just ignore page terminators, which are rarely used anyway.) But if I was writing this sort of code, I wouldn't worry about line endings at all, and simply encrypt the file as binary data, using Stream_IO to read it in and out. Randy.

 Hi Randy, I am not in that league of theoretical Ada that I can debate with any of you guys. For your info there are lots of New_Lines in the sample I submitted but I think there are other instances where there may be only one. My Ada programs have NEVER failed in thousands of runs - in fact they have never failed for any language syntax reason in about 10 years!. I am taking on board what you say is a definition of GET for pondering later. Can I tell you where I am coming from, Forget about programming my ciphers in the Ada language or any language. The cryptographic strength of the cipher depends on the veracity of the mathematical proof of the cipher algorithm alone. That in my case is written in stone. Demonstrating the cipher in Ada is the language I happen to greatly favour because of the workmanlike transparency of this langauge but the fact of my using gnat 311.p is merely a token and other updated gnat evrsions will always need to tested like right now 2013 version of MAC. Fundamentally, the crypto strength is both insured and assured beforehand regardless of how it runs in programs and if it fails for programmimg language reasons that is something that can be fixed and it is not as serious as being broken by cryptanalysis. 


I am of the belief there are always going to be problems to be expected when changing platforms like this. Up to now the programs to hand are very, very solid and even surprise me at the things they seem to shake off like encrypting source code so accurately where the smallest lack of fidelity could cause it to not run later on the decrypted sourcecode. I think that in the future each implementation on whatever platform is going to need tweaking initially but once that is done the natural stability of Ada will take over thereafter and when the cipher is wrtten it is there for all time. 

*It is hugely important for me to establish the fact that the cryptographic strength of my ciphers is ring-fenced independently of any langauge and may even be done in longhand fashion of push came to shove.

The class of these ciphers is demonstrably the ultimate clas of "Theoretically Unbreakable" and must not be undermined ever by whatever language is used - that is merely a conveyance - achieving cryptographic of perfect secercy is so difficult it is almost like a Greek Classic.

adacrypt.

^ permalink raw reply	[relevance 3%]

* Re: Will Ada-95 Programs Written in MS Windows Run in MacOS and Linux Without Some Tweaking.
    2013-12-10 11:39  4%             ` Austin Obyrne
@ 2013-12-11  0:34  5%             ` Simon Wright
  1 sibling, 0 replies; 200+ results
From: Simon Wright @ 2013-12-11  0:34 UTC (permalink / raw)


"Randy Brukardt" <randy@rrsoftware.com> writes:

> "Simon Wright" <simon@pushface.org> wrote in message 
> news:lywqjf45za.fsf@pushface.org...
> ...
>> I'm not sure of the best way to get an Ada program not to care what
>> sort of input line terminators it's reading.
>
> I'm surprised that that would be a problem, at least for Unix and
> Windows files. It's pretty simple to design Text_IO so that it can
> read either properly; that's how Text_IO in Janus/Ada works. (The only
> difference for it between Windows and Unix versions is the characters
> output by New_Line).

GNAT is certainly not as clever as that. On Mac OS X, this program

========================================================================
with Ada.Streams.Stream_IO;
with Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;

procedure S is

   Data_File_Name : constant String := "s.dat";
   Text_File : Ada.Text_IO.File_Type;

   procedure Write_As_Stream (Data : String) is
      package ASS renames Ada.Streams.Stream_IO;
      Stream_File : ASS.File_Type;
   begin
      ASS.Open (Stream_File,
                Name => Data_File_Name,
                Mode => ASS.Out_File);
      declare
         Stream_Access : constant ASS.Stream_Access
           := ASS.Stream (Stream_File); -- the file has to be open already
      begin
         String'Write (Stream_Access, Data);
      end;
      ASS.Close (Stream_File);
   end Write_As_Stream;

begin

   Put_Line ("testing \n");
   Write_As_Stream (String'(1 => ASCII.LF));
   Open (Text_File, Name => Data_File_Name, Mode => In_File);
   Put_Line ("EOL is " & Boolean'Image (End_Of_Line (Text_File)));
   Put_Line ("EOF is " & Boolean'Image (End_Of_File (Text_File)));
   Close (Text_File);

   Put_Line ("testing \r\n");
   Write_As_Stream (String'(1 => ASCII.CR, 2 => ASCII.LF));
   Open (Text_File, Name => Data_File_Name, Mode => In_File);
   Put_Line ("EOL is " & Boolean'Image (End_Of_Line (Text_File)));
   Put_Line ("EOF is " & Boolean'Image (End_Of_File (Text_File)));
   Close (Text_File);

   declare
      Dummy : Integer;
   begin
      Put_Line ("testing \n42");
      Write_As_Stream (String'(1 => ASCII.LF) & "42");
      Open (Text_File, Name => Data_File_Name, Mode => In_File);
      Ada.Integer_Text_IO.Get (Text_File, Dummy);
      Put_Line ("Value is " & Integer'Image (Dummy));
      Close (Text_File);
   end;

   declare
      Dummy : Integer;
   begin
      Put_Line ("testing \r\n42");
      Write_As_Stream (String'(1 => ASCII.CR, 2 => ASCII.LF) & "42");
      Open (Text_File, Name => Data_File_Name, Mode => In_File);
      Ada.Integer_Text_IO.Get (Text_File, Dummy);
      Put_Line ("Value is " & Integer'Image (Dummy));
      Close (Text_File);
   end;

end S;
========================================================================

results in

------------------------------------------------------------------------
testing \n
EOL is TRUE
EOF is TRUE
testing \r\n
EOL is FALSE
EOF is FALSE
testing \n42
Value is  42
testing \r\n42

Execution terminated by unhandled exception
Exception name: ADA.IO_EXCEPTIONS.DATA_ERROR
------------------------------------------------------------------------

whereas on a Windows machine I get

------------------------------------------------------------------------
testing \n
EOL is TRUE
EOF is TRUE
testing \r\n
EOL is TRUE
EOF is TRUE
testing \n42
Value is  42
testing \r\n42
Value is  42
------------------------------------------------------------------------

so I feel a bug report coming on .. 

> But if you don't want to change the terminators (or your compiler has an 
> unnecessarily inflexible Text_IO), I'd suggest using Stream_IO. Of course, 
> then you'll have to do your own buffering of input (but that's usually a 
> good idea anyway).

Yes. Actually I tried Sequential_IO, but for just reading Characters
there's not a lot of difference ... is there?


^ permalink raw reply	[relevance 5%]

* Re: Will Ada-95 Programs Written in MS Windows Run in MacOS and Linux Without Some Tweaking.
  2013-12-10 11:39  4%             ` Austin Obyrne
@ 2013-12-10 21:49  0%               ` Randy Brukardt
  2013-12-11 10:35  3%                 ` Austin Obyrne
  0 siblings, 1 reply; 200+ results
From: Randy Brukardt @ 2013-12-10 21:49 UTC (permalink / raw)



"Austin Obyrne" <austin.obyrne@hotmail.com> wrote in message 
news:2b6dc37f-4aa6-4c18-be59-8c09f6f37f01@googlegroups.com...
On Tuesday, December 10, 2013 6:37:28 AM UTC, Randy Brukardt wrote:
...
>Please consider this procedure in the program that gave trouble,
>
>This is the defacto stripped down procedure
>
>EXIT when EOF;
>  EXIT when EOL;
>
>    FOR I IN 1 .. 3 LOOP
>      Ada.Integer_Text_IO.Get(File => InData, Item => W(I));
>      --Ada.Integer_Text_IO.Put(Item => W(I), Width => 8);
>    END LOOP;
>
>LOOP;
>LOOP;

I presume that there is a New_Line in there somewhere so that the line 
endings aren't lost completely.

But this isn't going to work, as Get for a character is defined as follows: 
"After skipping any line terminators and any page terminators, reads the 
next character from the specified input file and returns the value of this 
character in the out parameter Item."

So if you have any line endings in between the 1st and 2nd characters (or 
between the 2nd and 3rd characters), you'll end up ignoring them. I doubt 
that's what you want. (Ada abstracts the line, page, and file terminators so 
you don't have to worry about how they're represented. The problem being 
that you *can't* see how they're represented if you are using Text_IO.)

Using Text_IO without losing line endings and the like is tricky. I 
generally don't bother, just reading a line at a time with Get_Line and then 
process whatever I get. (And I just ignore page terminators, which are 
rarely used anyway.)

But if I was writing this sort of code, I wouldn't worry about line endings 
at all, and simply encrypt the file as binary data, using Stream_IO to read 
it in and out.

                                    Randy.





^ permalink raw reply	[relevance 0%]

* Re: Will Ada-95 Programs Written in MS Windows Run in MacOS and Linux Without Some Tweaking.
  @ 2013-12-10 11:39  4%             ` Austin Obyrne
  2013-12-10 21:49  0%               ` Randy Brukardt
  2013-12-11  0:34  5%             ` Simon Wright
  1 sibling, 1 reply; 200+ results
From: Austin Obyrne @ 2013-12-10 11:39 UTC (permalink / raw)


On Tuesday, December 10, 2013 6:37:28 AM UTC, Randy Brukardt wrote:
> "Simon Wright" <simon@pushface.org> wrote in message news:lywqjf45za.fsf@pushface.org... ... > and as far as I can tell this was caused by the Windows line > terminator[2] in the data file; that's to say, when I removed the CR > character from the Windows CR/LF the program decoded correctly. > > I'm not sure of the best way to get an Ada program not to care what sort > of input line terminators it's reading. I'm surprised that that would be a problem, at least for Unix and Windows files. It's pretty simple to design Text_IO so that it can read either properly; that's how Text_IO in Janus/Ada works. (The only difference for it between Windows and Unix versions is the characters output by New_Line). Of course, such a Text_IO would make a real hash out of old Mac files. (I usually use an Ada program to convert text files to Windows format; it's just a simple loop of Get_Line/Put_Line pairs.) But if you don't want to change the terminators (or your compiler has an unnecessarily inflexible Text_IO), I'd suggest using Stream_IO. Of course, then you'll have to do your own buffering of input (but that's usually a good idea anyway). Randy.

Hi Randy,

May I chip in with this layman’s suggestion however daft it may seem to you guys (all my Ada has been learned by teasing out mechanical models that I invented and conjecture as being Ada syntax errors eliminating them one by one until it is compiled and built ok).  

*I am in Ada just for one solitary piece of problem solving i.e. the implementation of my ciphers in a programming language that I like so here goes.
I don't anything about what's under the bonnet of the Ada Rolls Royce.

Please consider this procedure in the program that gave trouble,

This is the defacto stripped down procedure

EXIT when EOF;
  EXIT when EOL;

    FOR I IN 1 .. 3 LOOP
      Ada.Integer_Text_IO.Get(File => InData, Item => W(I));
      --Ada.Integer_Text_IO.Put(Item => W(I), Width => 8);
    END LOOP;

LOOP;
LOOP;

The EOF marker on my computer is the right arrow => (element number 26 in Latin-1)

I don’t know what EOL is (yet)

Could it be that the 'FOR' loop is somehow getting out of sync with EOL ???? i.e. not being completed at the computer-perceived EOL ???

Fools rush in …..

Regards 

Austin - adacrypt

 

^ permalink raw reply	[relevance 4%]

* Re: Will Ada-95 Programs Written in MS Windows Run in MacOS and Linux Without Some Tweaking.
  @ 2013-12-07 18:26  4%       ` Austin Obyrne
    0 siblings, 1 reply; 200+ results
From: Austin Obyrne @ 2013-12-07 18:26 UTC (permalink / raw)


On Saturday, December 7, 2013 5:18:06 PM UTC, Simon Wright wrote:
> Austin Obyrne <austin.obyrne@hotmail.com> writes: > From what you have told me I think I should leave the dissemination of > the finished ciphers (currently to hand in Ada-95 only but required in > all the possible future versions of Ada) to experienced people who are > au fait with all the nuances of compilers that are available to day. The compilers I've tried with this are Ada2005 natively, and your programs also work with the -gnat12 (Ada 2012) switch. You might have tripped over new reserved words, but didn't, and since you haven't used access or tagged types or tasking I think you'd be pretty safe to upgrade your compiler. A couple of points: (a) when I encrypted Now is the time for all good men to come to the aid of the Party. ~ it decrypted as Now is the time for all good mento come to the aid of the Party.~ Is that meant to happen, or is there a problem with Windows line terminators (CR/LF) vs Unix (LF)? (b) when I decrypted Email_CipherTextFile_X.dat I got Execution terminated by unhandled exception Exception name: ADA.IO_EXCEPTIONS.DATA_ERROR and the exception was raised at line 683 of general_decryption_program_mark_2.adb.    

Hi Simon,

The second line down below is line 683

FOR I IN 1 .. 3 LOOP
      *=> Ada.Integer_Text_IO.Get(File => InData, Item => W(I));
      --Ada.Integer_Text_IO.Put(Item => W(I), Width => 8);
END LOOP;
 This appears to be ok to me ?

You are working from a very old edition of this program

Could I ask you to start again and download "SureCrypt Cipher" from 

http://www.adacryptpages.com
 
Sorry for the inconvenience - you are going great guns - the line numbers are difficult for me to trace today in the older program - Note - There is only one of each program in this more recent download.

I think there is always going to be some small errors - ideally I should liaise very closely with anybody such as yourself in any exercises like this.

Can you please spell out exactly which program you are referring to also because I have sometimes renamed them differently over the years in different uploads.

Ada-wise all these programs are the same -just extra refinements have been added now and then.

Thanks for what you are doing.

Austin  



^ permalink raw reply	[relevance 4%]

* Re: Beginner issue..
  2013-06-16  6:54  5% Beginner issue Marcus F
@ 2013-06-16  7:00  0% ` Marcus F
  0 siblings, 0 replies; 200+ results
From: Marcus F @ 2013-06-16  7:00 UTC (permalink / raw)


On Sunday, June 16, 2013 1:54:29 AM UTC-5, Marcus F wrote:
> Hi!
> 
> 
> 
> I'm Marcus, I'm completely new to ADA but not to programming.
> 
> I'm looking at a simple tutorial guide to pick up some basics of ADA, but I ran into an issue that I don't understand.
> 
> 
> 
> Here's the trivial example I followed:
> 
> 
> 
> with Ada.Text_IO, Ada.Integer_Text_IO;
> 
> use Ada.Text_IO, Ada.Integer_Text_IO;
> 
>  
> 
> procedure Compute is
> 
> 
> 
>  procedure Double(Item : in out Integer) is
> 
>  begin -- procedure Double.
> 
>    Item := Item * 2;
> 
>  end Double;
> 
> 
> 
>  X : Integer := 1;   -- Local variable X of type Integer.
> 
> 
> 
> begin -- procedure Compute
> 
>  loop
> 
>   Put(X);
> 
>   New_Line;
> 
>   Double(X);
> 
>  end loop;
> 
> end Compute;
> 
> 
> 
> 
> 
> Now, I expect X to double once per loop, but when I build and run, I just get 0's scrolling down my screen.
> 
> 
> 
> Could someone help out a newbie?

Let me rephrase that, I just removed the loop part, and the variable and Double seems fine, and displays the values I expect, but why would it just show a single line of 0's when in a loop?


^ permalink raw reply	[relevance 0%]

* Beginner issue..
@ 2013-06-16  6:54  5% Marcus F
  2013-06-16  7:00  0% ` Marcus F
  0 siblings, 1 reply; 200+ results
From: Marcus F @ 2013-06-16  6:54 UTC (permalink / raw)


Hi!

I'm Marcus, I'm completely new to ADA but not to programming.
I'm looking at a simple tutorial guide to pick up some basics of ADA, but I ran into an issue that I don't understand.

Here's the trivial example I followed:

with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
 
procedure Compute is

 procedure Double(Item : in out Integer) is
 begin -- procedure Double.
   Item := Item * 2;
 end Double;

 X : Integer := 1;   -- Local variable X of type Integer.

begin -- procedure Compute
 loop
  Put(X);
  New_Line;
  Double(X);
 end loop;
end Compute;


Now, I expect X to double once per loop, but when I build and run, I just get 0's scrolling down my screen.

Could someone help out a newbie?


^ permalink raw reply	[relevance 5%]

* Re: Simple loop with a strange output
  2013-05-23 13:53  5% Simple loop with a strange output Luca Cappelletti
@ 2013-05-23 13:55  0% ` Luca Cappelletti
  0 siblings, 0 replies; 200+ results
From: Luca Cappelletti @ 2013-05-23 13:55 UTC (permalink / raw)


Il giorno giovedì 23 maggio 2013 15:53:19 UTC+2, Luca Cappelletti ha scritto:
> Hello,
> 
> 
> 
> I'm using GNAT 4.6 via Debian 7
> 
> 
> 
> I've just compiled this simple code coming from a tutorial where I've just a little bit changed to fit my test:
> 
> 
> 
> 
> 
> with Ada.Text_IO, Ada.Integer_Text_IO;
> 
> use Ada.Text_IO, Ada.Integer_Text_IO;
> 
> procedure Hello is
> 
> 
> 
>     procedure Raddoppia(Elemento: in out Integer) is
> 
>     begin
> 
>     
> 
>         Elemento := Elemento * 2;
> 
>     
> 
>     end Raddoppia;
> 
> 
> 
> X : Integer;
> 
> 
> 
> begin
> 
> 
> 
>     Put_Line("start counting");
> 
>     New_Line;
> 
> 
> 
>     X := 1; 
> 
>     while X < 1009999999 loop
> 
>         Put(X);
> 
>         New_Line;
> 
>         Raddoppia(X);
> 
>     end loop;
> 
> 
> 
> end Hello;
> 
> 
> 
> that produce the expected:
> 
> 
> 
> $./hello
> 
> Ciao a tutti sto usando Put_Line direttamente con la clausola use
> 

sorry there was a paste error from 2 text files the right output was:

$ ./hello
Start counting

          1
          2
          4
          8
         16
         32
         64
        128
        256
        512
       1024
       2048
       4096
       8192
      16384
      32768
      65536
     131072
     262144
     524288
    1048576
    2097152
    4194304
    8388608
   16777216
   33554432
   67108864
  134217728
  268435456
  536870912

thanks

Luca

^ permalink raw reply	[relevance 0%]

* Simple loop with a strange output
@ 2013-05-23 13:53  5% Luca Cappelletti
  2013-05-23 13:55  0% ` Luca Cappelletti
  0 siblings, 1 reply; 200+ results
From: Luca Cappelletti @ 2013-05-23 13:53 UTC (permalink / raw)


Hello,

I'm using GNAT 4.6 via Debian 7

I've just compiled this simple code coming from a tutorial where I've just a little bit changed to fit my test:


with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure Hello is

    procedure Raddoppia(Elemento: in out Integer) is
    begin
    
        Elemento := Elemento * 2;
    
    end Raddoppia;

X : Integer;

begin

    Put_Line("start counting");
    New_Line;

    X := 1; 
    while X < 1009999999 loop
        Put(X);
        New_Line;
        Raddoppia(X);
    end loop;

end Hello;

that produce the expected:

$./hello
Ciao a tutti sto usando Put_Line direttamente con la clausola use

          1
          2
          4
          8
         16
         32
         64
        128
        256
        512
       1024
       2048
       4096
       8192
      16384
      32768
      65536
     131072
     262144
     524288
    1048576
    2097152
    4194304
    8388608
   16777216
   33554432
   67108864
  134217728
  268435456
  536870912


now that strange error:

if you change the code using only the simple "loop - end loop" or change the number into the while from 1009999999 to 1099999999

my output will be an infinite sequence of zero

$./hello
0
0
0
0
...
0
...



do you know what's happening?

thank in advance,

Luca

^ permalink raw reply	[relevance 5%]

* Re: How to get generic formal parameter type into base class
  @ 2012-10-11 23:52  4%         ` Georg Bauhaus
  0 siblings, 0 replies; 200+ results
From: Georg Bauhaus @ 2012-10-11 23:52 UTC (permalink / raw)


On 11.10.12 22:25, kevin andrew wrote:

> FYI, you can do this with C++ template classes, and though I have
> never tried, Java has added templates as well.

Like the C++ version, this establishes the required
relationship between Int and Char; C++'s protected
visibility is achieved with the help of a child package.

package Typedef is
    
    subtype Value_T is Integer;
    
end Typedef;

with Typedef; use Typedef;

generic
    type T is new Value_T;
package BaseClass is
    
    type BaseClass is tagged private;
    procedure Decode (Item : in out BaseClass; Value: Value_T) is null;
    function GetValue (Item : BaseClass) return T;
private
    type BaseClass is tagged record
       Data : T;
       Value : Value_T;
    end record;
end BaseClass;

package body Baseclass is
    Default : T;
    function GetValue (Item : BaseClass) return T is
    begin
       return Default;
    end GetValue;
    
end Baseclass;

with Typedef; use Typedef;
generic
    type T is new Value_T;
package BaseClass.NewClass is
    type NewClass is new BaseClass with private;
    overriding procedure Decode (Item : in out NewClass; Value: Value_T);
    overriding function GetValue (Item : NewClass) return Standard.BaseClass.T;
private
    type NewClass is new BaseClass with null record;
end BaseClass.NewClass;

package body BaseClass.NewClass is
    overriding procedure Decode (Item : in out NewClass; Value: Value_T) is
    begin
       Item.Value := Value;
       Item.Data := STandard.BaseClass.T(Value);
    end Decode;
    
    overriding function GetValue (Item : NewClass) return Standard.BaseClass.T is
    begin
       return Item.Data;
    end Getvalue;
end BaseClass.NewClass;

    
with Typedef; use Typedef;
with BaseClass.NewClass;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure main is
    
    subtype Int is Integer range Integer'Range;
    subtype Char is Integer range -128 .. 127;
    
    package BaseClassInstance is new BaseClass(Int);
    package NewClassInt is new BaseClassInstance.NewClass(Int);
    IntClass: NewClassInt.NewClass;
    
    package BaseClassInstance2 is new BaseClass(Char);
    package NewClassChar is new BaseClassInstance2.NewClass(Char);
    CharClass: NewClassChar.NewClass;
    
    Value : Value_T := 4;
begin
    IntClass.Decode(Value);
    declare
       I : Integer := IntClass.GetValue;
    begin
       Value := 97;
       CharClass.Decode(Value);
       declare
          Ch: Char := CharClass.GetValue;
          use Ada.Text_IO, Ada.Integer_Text_IO;
       begin
          Default_Width := 0;
          Put ("int="); Put(I); Put("  ch="); Put (Character'Val(Ch)); New_Line;
       end;
    end;
end Main;





^ permalink raw reply	[relevance 4%]

* can Ada give run-time error or warning for integer division with non-zero remainder?
@ 2012-08-12  1:14  5% Nasser M. Abbasi
  2012-08-12  6:45  0% ` Dmitry A. Kazakov
                   ` (2 more replies)
  0 siblings, 3 replies; 200+ results
From: Nasser M. Abbasi @ 2012-08-12  1:14 UTC (permalink / raw)



In Ada when dividing 2 integers, the result is an integer
with the remainder ignored.  Hence 3/2 gives 1

----------------------------------
with Ada.Integer_Text_IO ; use Ada.Integer_Text_IO ;

procedure foo4 is
   N : constant integer := 3;
   M : integer;
   
   begin
     M := N/2;
     put(M);
        
end foo4;
--------------------------

>gnatmake foo4.adb
>./foo4
           1

Now, suppose I want to know that a division between 2 integers
has resulted in nonzero remainder that was thrown away. May be
because my algorithm is meant to work only for even values and
an odd value means there was a bug somewhere and I want to
know about it.

Is there any kind of run-time switch to tell it to
check for this? I know I can always add logic myself to
check for this in the code, using rem() for example (which
might be the better solution actually) but I was just
wondering if there is a run-time switch for this.

thanks,
-Nasser



^ permalink raw reply	[relevance 5%]

* Re: can Ada give run-time error or warning for integer division with non-zero remainder?
  2012-08-12  1:14  5% can Ada give run-time error or warning for integer division with non-zero remainder? Nasser M. Abbasi
  2012-08-12  6:45  0% ` Dmitry A. Kazakov
  2012-08-12  7:16  0% ` Per Sandberg
@ 2012-08-12 14:19  0% ` Robin Vowels
  2 siblings, 0 replies; 200+ results
From: Robin Vowels @ 2012-08-12 14:19 UTC (permalink / raw)


On Aug 12, 11:14 am, "Nasser M. Abbasi" <n...@12000.org> wrote:
> In Ada when dividing 2 integers, the result is an integer
> with the remainder ignored.  Hence 3/2 gives 1
>
> ----------------------------------
> with Ada.Integer_Text_IO ; use Ada.Integer_Text_IO ;
>
> procedure foo4 is
>    N : constant integer := 3;
>    M : integer;
>
>    begin
>      M := N/2;
>      put(M);
>
> end foo4;
> --------------------------
>
> >gnatmake foo4.adb
> >./foo4
>
>            1
>
> Now, suppose I want to know that a division between 2 integers
> has resulted in nonzero remainder that was thrown away. May be
> because my algorithm is meant to work only for even values and
> an odd value means there was a bug somewhere and I want to
> know about it.

Use MOD.




^ permalink raw reply	[relevance 0%]

* Re: can Ada give run-time error or warning for integer division with non-zero remainder?
  2012-08-12  1:14  5% can Ada give run-time error or warning for integer division with non-zero remainder? Nasser M. Abbasi
  2012-08-12  6:45  0% ` Dmitry A. Kazakov
@ 2012-08-12  7:16  0% ` Per Sandberg
  2012-08-12 14:19  0% ` Robin Vowels
  2 siblings, 0 replies; 200+ results
From: Per Sandberg @ 2012-08-12  7:16 UTC (permalink / raw)


If you want an new behaviour for "/" on an integer type you could always
make a new integer type with the required properties:
-------------------------------------------------------------------------
package Integers is
   type Integer is new Standard.Integer;
   overriding function "/" (L : Integer; R  : Integer) return Integer;
   function "/" (L : Standard.Integer; R  : Integer) return Integer;
   function "/" (L : Integer; R  : Standard.Integer) return Integer;
end Integers
-------------------------------------------------------------------------
package body Integers is

   overriding function "/" (L : Integer; R  : Integer) return Integer is
   begin
      return Ret : Integer do
         Ret := Integer (Standard.Integer (Standard.Integer (L) /
   Standard.Integer (R))); if Ret * R /= L then
            raise Constraint_Error with L'Img & "/" & R'Img & " gives
   reminder."; end if;
      end return;
   end "/";

   function "/" (L : Standard.Integer; R  : Integer) return Integer is
   begin
      return Ret : Integer do
         Ret := Integer (L) / R;
      end return;
   end "/";

   function "/" (L : Integer; R  : Standard.Integer) return Integer is
   begin
      return Ret : Integer do
         Ret := L / Integer (R);
      end return;
   end "/";

end Integers;
-------------------------------------------------------------------------
/P


On Sat, 11 Aug 2012 20:14:42 -0500 "Nasser M. Abbasi" <nma@12000.org>
wrote:

> 
> In Ada when dividing 2 integers, the result is an integer
> with the remainder ignored.  Hence 3/2 gives 1
> 
> ----------------------------------
> with Ada.Integer_Text_IO ; use Ada.Integer_Text_IO ;
> 
> procedure foo4 is
>    N : constant integer := 3;
>    M : integer;
>    
>    begin
>      M := N/2;
>      put(M);
>         
> end foo4;
> --------------------------
> 
> >gnatmake foo4.adb
> >./foo4
>            1
> 
> Now, suppose I want to know that a division between 2 integers
> has resulted in nonzero remainder that was thrown away. May be
> because my algorithm is meant to work only for even values and
> an odd value means there was a bug somewhere and I want to
> know about it.
> 
> Is there any kind of run-time switch to tell it to
> check for this? I know I can always add logic myself to
> check for this in the code, using rem() for example (which
> might be the better solution actually) but I was just
> wondering if there is a run-time switch for this.
> 
> thanks,
> -Nasser





^ permalink raw reply	[relevance 0%]

* Re: can Ada give run-time error or warning for integer division with non-zero remainder?
  2012-08-12  1:14  5% can Ada give run-time error or warning for integer division with non-zero remainder? Nasser M. Abbasi
@ 2012-08-12  6:45  0% ` Dmitry A. Kazakov
  2012-08-12  7:16  0% ` Per Sandberg
  2012-08-12 14:19  0% ` Robin Vowels
  2 siblings, 0 replies; 200+ results
From: Dmitry A. Kazakov @ 2012-08-12  6:45 UTC (permalink / raw)


On Sat, 11 Aug 2012 20:14:42 -0500, Nasser M. Abbasi wrote:

> In Ada when dividing 2 integers, the result is an integer
> with the remainder ignored.  Hence 3/2 gives 1
> 
> ----------------------------------
> with Ada.Integer_Text_IO ; use Ada.Integer_Text_IO ;
> 
> procedure foo4 is
>    N : constant integer := 3;
>    M : integer;
>    
>    begin
>      M := N/2;
>      put(M);
>         
> end foo4;
> --------------------------
> 
>>gnatmake foo4.adb
>>./foo4
>            1
> Now, suppose I want to know that a division between 2 integers
> has resulted in nonzero remainder that was thrown away. May be
> because my algorithm is meant to work only for even values and
> an odd value means there was a bug somewhere and I want to
> know about it.

It is not integer division then. You could use integer interval division
instead: [3, 3] / [2, 2] = [1, 2].

-- 
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de



^ permalink raw reply	[relevance 0%]

* “Parallel Sort” Program in Essence.
@ 2012-07-04  7:48  4% Austin Obyrne
  0 siblings, 0 replies; 200+ results
From: Austin Obyrne @ 2012-07-04  7:48 UTC (permalink / raw)



SUBTYPE Index_2 IS Integer RANGE 0 .. 1000009;
TYPE I_CoefficientsNumArray IS ARRAY(Index_2) OF Integer;
I_Num : I_CoefficientsNumArray := (others =>0); -- initialises array
-- places the numbers for sorting  in an array.

Data Collection.

Q := NextNum(I);
I_NUM(Q):= I_NUM(Q)+1;

Sorting.

FOR I IN 0  .. 1000000 LOOP  -- Sort Program proper starts here. 
  IF I_Num(I) /= 0 THEN
    Counter:= I_Num(I);
      FOR J in 1 .. Counter LOOP
        Ada.Integer_Text_IO.Put(File => Outdata, Item =>  (I));--
        Ada.Text_IO.New_Line;
        Check := Check +1;
        Sorted(Check):= I;
      END LOOP;
  END IF;
END LOOP;

Austin O'Byrne.

- adacrypt



^ permalink raw reply	[relevance 4%]

* Re: how to print an array range?
  2012-06-26 13:47  5% how to print an array range? Nasser M. Abbasi
  @ 2012-06-28  6:59  0% ` Shark8
  1 sibling, 0 replies; 200+ results
From: Shark8 @ 2012-06-28  6:59 UTC (permalink / raw)
  Cc: nma

On Tuesday, June 26, 2012 8:47:01 AM UTC-5, Nasser M. Abbasi wrote:
> simple question from newbie. How do I print array range?
> I tried using image' attribute, but can't get the syntax to
> work right.
> 
> ----------------------------
> with Ada.Text_Io; use Ada.Text_Io;
> with Ada.Float_Text_Io; use Ada.Float_Text_Io;
> with Ada.integer_Text_Io; use Ada.integer_Text_Io;
> with Ada.Numerics.Real_Arrays;  use Ada.Numerics.Real_Arrays;
> 
> procedure foo1 is
>      A : constant Real_Matrix :=
>               (( 1.0,  2.0,  3.0),
>                ( 4.0,  5.0,  6.0),
>                ( 7.0,  8.0,  9.0));
> begin
> 
>      put(A'range(1));
>      
> end foo1;
> ----------------------
> 
> I expected to see "1..3". How do you use image' on this
> or other way to display the range?
> 
> thanks,
> --Nasser

Ok, let's say you have Array_Type which is defined as Array (Integer Range <>) of Integer. We can achieve this by the following function:

Procedure Put_Range( A : In Array_Type ) is
  Use Text_IO, Integer_IO;
begin
  Put( A'First );
  Put( ".." );
  Put( A'Last );
end Put_Range;

For a mulch-dimensional array you would do something similar either a) calling the given function as an iteration through the minor-index, or b) expanding the above with the 'Range(Index_Number) attribute. {If I remember the attribute name correctly.}



^ permalink raw reply	[relevance 0%]

* Re: how to print an array range?
  @ 2012-06-26 19:28  5%               ` John B. Matthews
  0 siblings, 0 replies; 200+ results
From: John B. Matthews @ 2012-06-26 19:28 UTC (permalink / raw)


In article <4fe9edc7$0$6570$9b4e6d93@newsspool4.arcor-online.net>,
 Georg Bauhaus <rm.dash-bauhaus@futureapps.de> wrote:

> On 26.06.12 19:05, John B. Matthews wrote:
> 
> > Ada.Text_IO.Put_Line(A'First'Img & " " & A'Last'Img);
> 
> In case anyone wishes to write standard Ada when debugging,
> not the GNAT language, the implementation specific attribute
> 'Img can be replaced by standard Ada's
> 
> Ada.Text_IO.Put_Line
>   (Integer'Image(A'First) & " " & Integer'Image(A'Last));
> 
> The static member functions of class Integer ;-)

Nasser: This is absolutely correct about Ada, and a helpful point of 
reference in Java; see also the static member functions of class String.

For more control over width and base, instantiate Integer_IO:

package Ada.Integer_Text_IO is new Ada.Text_IO.Integer_IO (Integer);

An instance of which may already exist in one's library:

with Ada.Integer_Text_IO;

You might also like to compare these two projects that implement the 
same root finding algorithm and test program in Ada and Java:

<http://home.roadrunner.com/~jbmatthews/misc/groots.html>
<http://sites.google.com/site/drjohnbmatthews/polyroots>

-- 
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>



^ permalink raw reply	[relevance 5%]

* Re: how to print an array range?
  2012-06-26 14:08  5%   ` Nasser M. Abbasi
@ 2012-06-26 14:24  5%     ` Nasser M. Abbasi
    0 siblings, 1 reply; 200+ results
From: Nasser M. Abbasi @ 2012-06-26 14:24 UTC (permalink / raw)


On 6/26/2012 9:08 AM, Nasser M. Abbasi wrote:
...
>       put(A'First(1)); new_line;
>       put(A'Last(1));
>
> end foo1;
> ----------------------------
>
>> gnatmake foo1.adb
> gcc-4.6 -c foo1.adb
> gnatbind -x foo1.ali
> gnatlink foo1.ali
>> ./foo1
> -2147483648
> -2147483646

I think I know what these numbers are. Look like Integer'first.

But I wanted to see the range of
the first dimension of the Matrix A below. (1..3, 1..3)

----------------------------------
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.integer_Text_Io; use Ada.integer_Text_Io;
with Ada.Numerics.Real_Arrays;  use Ada.Numerics.Real_Arrays;

procedure foo1 is
      A : constant Real_Matrix :=
               (( 1.0,  2.0,  3.0),
                ( 4.0,  5.0,  6.0),
                ( 7.0,  8.0,  9.0));
begin

      put(A'First(1)); new_line;
      put(A'Last(1));
          
end foo1;
-------------------------------

I think I Will go hunt for a book on Ada, and will
look at the packages Dmitry just posted.

thanks,

--Nasser



^ permalink raw reply	[relevance 5%]

* Re: how to print an array range?
  @ 2012-06-26 14:08  5%   ` Nasser M. Abbasi
  2012-06-26 14:24  5%     ` Nasser M. Abbasi
  0 siblings, 1 reply; 200+ results
From: Nasser M. Abbasi @ 2012-06-26 14:08 UTC (permalink / raw)


On 6/26/2012 8:54 AM, Georg Bauhaus wrote:
> On 26.06.12 15:47, Nasser M. Abbasi wrote:
>>
>> simple question from newbie. How do I print array range?
>
> A range is not a value of some type.
>
> For type T, print T'First and T'Last; for array A(..., ...),
> print A'First(n) and A'Last(n), n > 0 being the nth index type.
>

Ok fair enough.
btw, would you know by any chance why I get these values?

----------------------------------
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.integer_Text_Io; use Ada.integer_Text_Io;
with Ada.Numerics.Real_Arrays;  use Ada.Numerics.Real_Arrays;

procedure foo1 is
     A : constant Real_Matrix :=
              (( 1.0,  2.0,  3.0),
               ( 4.0,  5.0,  6.0),
               ( 7.0,  8.0,  9.0));
begin

     put(A'First(1)); new_line;
     put(A'Last(1));
         
end foo1;
----------------------------

>gnatmake foo1.adb
gcc-4.6 -c foo1.adb
gnatbind -x foo1.ali
gnatlink foo1.ali
>./foo1
-2147483648
-2147483646
>

I know I am doing something silly here.

(I feel I have so much catching to do with Ada)

--Nasser



^ permalink raw reply	[relevance 5%]

* how to print an array range?
@ 2012-06-26 13:47  5% Nasser M. Abbasi
    2012-06-28  6:59  0% ` Shark8
  0 siblings, 2 replies; 200+ results
From: Nasser M. Abbasi @ 2012-06-26 13:47 UTC (permalink / raw)



simple question from newbie. How do I print array range?
I tried using image' attribute, but can't get the syntax to
work right.

----------------------------
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.integer_Text_Io; use Ada.integer_Text_Io;
with Ada.Numerics.Real_Arrays;  use Ada.Numerics.Real_Arrays;

procedure foo1 is
     A : constant Real_Matrix :=
              (( 1.0,  2.0,  3.0),
               ( 4.0,  5.0,  6.0),
               ( 7.0,  8.0,  9.0));
begin

     put(A'range(1));
     
end foo1;
----------------------

I expected to see "1..3". How do you use image' on this
or other way to display the range?

thanks,
--Nasser



^ permalink raw reply	[relevance 5%]

* Re: In case you need to remember...
  @ 2012-04-06 20:09  4% ` anon
  0 siblings, 0 replies; 200+ results
From: anon @ 2012-04-06 20:09 UTC (permalink / raw)


The truth is Ada is Concurrent which means Ada uses one and only one 
thread for all tasks. 


And on a multiple core system the thread may swap between processors 
during thread scheduling but the Ada code is only one thread under 
the OS.  The RM 2012 does have some multiple processors packages but 
they are not enough routines to build a fully functioning true multiple 
thread for each task.

Now, GNAT using OS_Lib packages does have some OS links that can request 
new thread but these routines are not listed in the RM. Also, GNAT can 
use the Spawn or folk call but it is not recommended due to fact of 
blocking and signal/locks which are unpredictable. (see Note in 
System.OS_Lib.ads) Now in GNAT 2012 release in a month or two this 
may be different.


And example to demonstrated Ada based thread:


with Ada.Text_IO ;
with Ada.Integer_Text_IO ;
with Ada.Task_Identification ;

--  If Ada was multiple tasking using threads then the main procedure 
--  would end and the Task would run in the background similar to 
--  starting a server on any OS. This is, the main procedure would 
--  be use to active the task and then exit. But due to the fact that 
--  Ada is still concurrent the main procedure will finish executing 
--  but will be blocked in "Finalization".  Some resources may be 
--  release but not all. In other words the main procedure will be 
--  blocked and some resources held until the "Task" ends it run or 
--  the operator kills the executing thread which kills both the 
--  main procedure and the task and release all resources.
--
--  Also if you use a thread monitor you will see only one thread
--  was created and is running. And if Ada used multiple threads then 
--  in this program there would be one thread for the main procedure
--  "Test" and a second thread for the task "Task_1". But there is 
--  only one thread indicating that Ada is still concurrent.
--

procedure Test is

  use Ada ;
  use Text_IO ;
  use Integer_Text_IO ;


  task type CPU_TASK is
    entry Run_cpu ;  
  end CPU_TASK ;

  PC : Integer := 55 ;
  Run_Flag : Boolean := False ;

  --  Task is activated once the program begins
  --  If Ada was multiple thread then this task would activated once 
  --  the OS created a new thread entry in the job thread scheduler
  Task_1 : CPU_TASK ;  


  task body CPU_TASK is

    begin -- CPU_TASK 

      Put_Line ( "Processor is Uninitialized" ) ;
      loop
        select
          accept Run_cpu ;      

              -- Run until process is either reset, halted.  

              Put_Line ( "Task is in RUN Mode" ) ;
              Run_Flag := True ;
              loop
                Put_Line ( "Executed Instruction" & PC'img ) ;
                PC := PC + 1 ;
                Delay  0.0 ; -- tells Ada RTL to swap task to main
              end loop ;
              exit ;
        or
         terminate ;
        end select ;
      end loop ;
    end CPU_TASK ;

begin

  Put_Line ( "Reset Processor status" ) ;
  PC := 0 ;
  Delay 0.1 ;
  Put_Line ( "Set processor status to RUN Task" ) ;
  Task_1.Run_cpu ;

  Delay  0.5 ;
  Put_Line ( "Trying to Single Step Task" ) ;


--  Delay  0.1 ;
--  Put_Line ( "Stopping the Task" ) ;
--  Ada.Task_Identification.Abort_Task ( Task_1 ' Identity ) ;

    Put_Line ( "Finished Excution of program" ) ;
end test ;

In <1984433.261.1333725652284.JavaMail.geo-discussion-forums@vbbfr18>, mockturtle <framefritti@gmail.com> writes:
>....how nice is having tasks built-in in your preferred language, I just lan=
>ded over this text (Threads =97 Threat or Menace?)
>
>   http://www.faqs.org/docs/artu/ch07s03.html#id2923889
>
>Just an excerpt:=20
>
>  "Threads are a fertile source of bugs because they can too easily know to=
>o much about each others' internal states. There is no automatic encapsulat=
>ion, as there would be between processes with separate address spaces that =
>must do explicit IPC to communicate. Thus, threaded programs suffer from no=
>t just ordinary contention problems, but from entire new categories of timi=
>ng-dependent bugs that are excruciatingly difficult to even reproduce, let =
>alone fix."
>
>Hmm... Why do I have this warm and cozy feeling? :-)=20
>
>BTW, a curiosity: does the Linux version of GNAT use threads to implement t=
>asks?=20
>
>Riccardo




^ permalink raw reply	[relevance 4%]

* Re: Ada and linux real time
  @ 2012-03-17 15:50  4%                   ` Simon Wright
  0 siblings, 0 replies; 200+ results
From: Simon Wright @ 2012-03-17 15:50 UTC (permalink / raw)


Simon Wright <simon@pushface.org> writes:

> I was under the impression that the PREEMPT RT kernel "just" made the
> standard primitives more predictable & hence suitable for RT.
>
> I found http://pengutronix.de/software/linux-rt/debian_en.html and was
> going to have a go, but it looks as though they only support sid and I
> don't plan to update just yet!

There seems to be some real-time-ness in the standard Debian squeeze
kernel (2.6.32???).

This is a demo program - I made the delay 12 ms in case the OS tick was
10 ms; it isn't.

with Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;

procedure Check_Real_Time is
   --  Accumulates a histogram of the actual time taken by a notional
   --  12-ms delay. The bucket size is 0.01 ms.
   --
   --  Only prints out the non-zero buckets.
   subtype Bucket_Index is Natural range 0 .. 40000;
   Buckets : array (Bucket_Index) of Natural := (others => 0);
   use type Ada.Calendar.Time;
   Next : Ada.Calendar.Time;
begin
   Next := Ada.Calendar.Clock;
   for J in 1 .. 1000 loop
      declare
	 Start : constant Ada.Calendar.Time := Ada.Calendar.Clock;
	 Actual_Interval : Natural;  -- in hundredth-milliseconds
      begin
	 Next := Next + 0.012;
	 delay until Next;
	 Actual_Interval := Natural ((Ada.Calendar.Clock - Start) * 100_000.0);
	 if Actual_Interval > Buckets'Last then
	    Buckets (Buckets'Last) := Buckets (Buckets'Last) + 1;
	 else
	    Buckets (Actual_Interval) := Buckets (Actual_Interval) + 1;
	 end if;
      end;
   end loop;
   for J in Buckets'Range loop
      if Buckets (J) > 0 then
	 Put (J, Width => 5);
	 Put (Buckets (J), Width => 5);
	 New_Line;
      end if;
   end loop;
end Check_Real_Time;

Running the program wthout any special treatment:

   root@flambard:/home/simon# ./check_real_time 
    1120    1
    1136    1
    1163    1
    1165    1
    1176    1
    1189    1
    1191    2
    1197    1
    1198   32
    1199   36
    1200  852
    1201   24
    1202   36
    1203    1
    1204    1
    1208    1
    1209    1
    1210    1
    1211    1
    1225    1
    1235    1
    1238    1
    1264    1
    1280    1

Running the program at elevated but non-real-time priority:

   root@flambard:/home/simon# nice -1 ./check_real_time 
    1098    1
    1099    1
    1125    1
    1136    1
    1148    1
    1153    1
    1165    1
    1182    1
    1183    1
    1184    1
    1186    1
    1191    1
    1193    1
    1195    2
    1197    3
    1198   37
    1199   18
    1200  860
    1201   14
    1202   34
    1203    1
    1204    1
    1205    2
    1208    1
    1209    2
    1215    1
    1217    2
    1218    1
    1231    1
    1236    1
    1247    1
    1253    1
    1263    1
    1272    1
    1275    1
    1302    1

Running the program with elevated real-time priority:

   root@flambard:/home/simon# chrt 1 ./check_real_time 
    1194    1
    1195    1
    1198   37
    1199   26
    1200  872
    1201   22
    1202   35
    1203    4
    1206    1
    1208    1

Not perfect, but much better! (by the way, there was no other
user-generated load).



^ permalink raw reply	[relevance 4%]

* Re: Need Help On Ada95 Problem
  @ 2012-02-12 19:40  5%             ` Will
  0 siblings, 0 replies; 200+ results
From: Will @ 2012-02-12 19:40 UTC (permalink / raw)


Here Is The Solution and it does work so all of you can understand.  I
am fairly new to Ada95 so I have not been introduced to Arrays and
Case and all that stuff but I do understand the solutions here. I did
use the ASCII table and if you view it and go through this by hand you
will understand why it works. The solutions are as follows:



with Ada.Text_IO; use Ada.Text_IO;

with Ada.Characters.Handling; use Ada.Characters.Handling;

with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

with Ada.Strings.Fixed; use Ada.Strings.Fixed;



procedure hw4 is



   function Encrypt(PIN : String) return String is

      -- Convert the 4-digit PIN to the corresponding 4-letter code.

      -- Assume PIN'Length is 4 and that all the characters in PIN are
digits.

      -- Example: Encrypt("9537") = "ELVI"



      -- FILL IN FOUR MORE TEST CASES.

		--Test Case 1: Encrypt("6789") = "TINE"

		--Test Case 2: Encrypt("5432") = "LAVO"

		--Test Case 3: Encrypt("0926") = "UEOT"

		--Test Case 4: Encrypt("7359") = "IVLE"

		letterWheel : string := "UROVALTINE";

		password : string := PIN;

		counter : integer := 1;

		number : Character := '0';

		AdaIsHard : integer :=0 ;

begin

while counter <= 4 loop

number:= password(counter);

AdaIsHard := (Character'Pos(number)- 47);

password(counter):= letterWheel(AdaIsHard);

counter := counter + 1;

 end loop;

      return password;

   end Encrypt;



^ permalink raw reply	[relevance 5%]

* Re: Need Help On Ada95 Problem
  @ 2012-02-10  5:32  5%       ` Alex
    0 siblings, 1 reply; 200+ results
From: Alex @ 2012-02-10  5:32 UTC (permalink / raw)


Sure you can just use 'Pos! While the positions of the digit characters
do not correspond directly to their values, they are sequential in the
ASCII mapping, so all you have to do is subtract the position of the
Character '0' from each one to calculate its value. Check it out:

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is

begin

   for I in Character'('0') .. Character'('9') loop
      Put(Character'Pos(I) - Character'Pos('0'));
      New_Line;
   end loop;

end Main;



Shark8 wrote:

> On Feb 9, 7:36�pm, BrianG <m...@null.email> wrote:
> > On 02/08/2012 09:01 PM, Shark8 wrote:
> > 
> > 
> > 
> > 
> > 
> > 
> > 
> > 
> > 
> > > On Feb 8, 7:03 pm, Will<willmann...@gmail.com> �wrote:
> > >> I am new to Ada and need help on an exercise for school. �Can
> > anyone >> help. �The problem is as follows ( you can skip all the
> > build up >> background A Christmas Story references):
> > 
> > >> Problem 1: Secret Decoder Ring
> > ...
> > >> � � � number wheel -> � � �0 �1 �2 �3 �4 �5 �6 �7 �8 �9
> > >> � � � letter wheel -> � � �U �R �O �V �A �L �T �I �N �E
> > 
> > >> So, for example, Randy encrypts the PIN 9537 as ELVI.
> > 
> > >> Complete the function Encrypt(PIN) that takes a 4-digit PIN (as a
> > >> string) and returns the corresponding 4-letter code (also as a
> > >> string).
> > 
> > >> Note: It would be possible to convert digits to letters using a
> > giant >> IF statement, but don't do this. Instead, the letter wheel
> > is given to >> you as a string, so use each digit to read the
> > appropriate letter from >> the string.
> > 
> > > Alright this is actually a simple problem; there are several ways
> > > to go about this,
> > > but let's play to Ada's strengths and use types.
> > 
> > ...
> > > Reading the problem the note says:
> > > It would be possible to convert digits to letters using a giant
> > > IF statement, but don't do this. Instead, the letter wheel is
> > > given to you as a string, so use each digit to read the
> > > appropriate letter from the string.
> > 
> > > Meaning that they're hinting strongly that you use the CASE
> > > statement.
> > 
> > I don't see why this would require either an if or a case.
> > 
> > --
> > ---
> > BrianG
> > 000
> > @[Google's email domain]
> > .com
> 
> Well, you COULD use Ada's Maps; but that's just going to do the same
> thing: you still have to define the mapping.
> You can't just index into Character (via 'POS, 'VAL and index-
> manipulation) because the mapping isn't sequential;
> or even partly-sequential in the ASCII codes.
> 
> See the (3,4,5) association with (V,A,L) and (6,7,8) with (T,I,N).



^ permalink raw reply	[relevance 5%]

* Re: I need feedback
  2011-06-16  4:24  5%       ` juanmiuk
@ 2011-06-16  7:34  0%         ` Ludovic Brenta
  0 siblings, 0 replies; 200+ results
From: Ludovic Brenta @ 2011-06-16  7:34 UTC (permalink / raw)


juanmiuk wrote:
> Well, Thank you for all suggestion, I think I follow all of them.
> There you go the final version:
>
> with Ada.Text_IO;
> with Ada.Integer_Text_IO;
> with Ada.Numerics.Discrete_Random;
> with Ada.Strings.Fixed;
>
> use Ada;
> use Ada.Strings.Fixed;
>
> procedure Sort_3_Numbers is
>
>         subtype One_Ten is Integer range 1 .. 10;
>
>         package Roulette10 is new Ada.Numerics.Discrete_Random(One_Ten);
>
>         Gen10: Roulette10.Generator;
>
>    WIDTH_NUM : constant One_Ten := One_Ten'Width;
>    THE_BASE  : constant One_Ten := 10;

This is not necessary, see why below.

>    procedure Output_Num
>       ( The_Number : in     One_Ten;
>         Width_Num  : in     One_Ten;
>         The_Base   : in     One_Ten )
>    is
>
>    begin
>
>       Integer_Text_IO.Put(The_Number, Width_Num, The_Base);
>
>    end Output_Num;

This entire procedure does nothing but call Integer_Text_IO.Put, so is
not necessary; you might as well call Integer_Text_IO.Put directly.
In the spec of Integer_Text_IO.Put, the parameter Base has a default
value of 10, so you need not specify it.  You could even do away with
Width_Num like this:

package One_Ten_IO is new Ada.Text_IO.Integer_IO (Num => One_Ten);

This would initialize the constant One_Ten_IO.Default_Width to be
One_Ten'Width; you would not have to do it yourself.

> begin
>    Roulette10.Reset(Gen10);
>    for I in One_Ten'Range loop
>       Main_Process : declare
>          A               : One_Ten := Roulette10.Random(Gen10);
>          B               : One_Ten := Roulette10.Random(Gen10);
>          C               : One_Ten := Roulette10.Random(Gen10);
>
>          First   : One_Ten;
>          Secon   : One_Ten;
>          Third   : One_Ten;
>       begin
>          Output_Num(A, WIDTH_NUM, THE_BASE);
>          -- Changing all the Output_Num by Integer_Text_IO.Put(A, WIDTH_NUM, THE_BASE)
>          -- as Jeffrey Carter comments then won't be any dupplications.

Or, even more succinctly:

           One_Ten_IO.Put (A);

[rest snipped].

Hope this helps.

--
Ludovic Brenta.



^ permalink raw reply	[relevance 0%]

* Re: I need feedback
  @ 2011-06-16  4:24  5%       ` juanmiuk
  2011-06-16  7:34  0%         ` Ludovic Brenta
  0 siblings, 1 reply; 200+ results
From: juanmiuk @ 2011-06-16  4:24 UTC (permalink / raw)


Well, Thank you for all suggestion, I think I follow all of them.
There you go the final version:


with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;

use Ada;
use Ada.Strings.Fixed;

procedure Sort_3_Numbers is

	subtype One_Ten is Integer range 1 .. 10;

	package Roulette10 is new Ada.Numerics.Discrete_Random(One_Ten);

	Gen10: Roulette10.Generator;

   WIDTH_NUM : constant One_Ten := One_Ten'Width;
   THE_BASE  : constant One_Ten := 10;

   procedure Output_Num
      ( The_Number : in     One_Ten;
        Width_Num  : in     One_Ten;
        The_Base   : in     One_Ten )
   is

   begin

      Integer_Text_IO.Put(The_Number, Width_Num, The_Base);

   end Output_Num;

begin

	Roulette10.Reset(Gen10);
	for I in One_Ten'Range loop

   		Main_Process : declare

			A		: One_Ten := Roulette10.Random(Gen10);
			B		: One_Ten := Roulette10.Random(Gen10);
			C		: One_Ten := Roulette10.Random(Gen10);

			First	: One_Ten;
			Secon	: One_Ten;
			Third	: One_Ten;

   		begin

            Output_Num(A, WIDTH_NUM, THE_BASE);
            -- Changing all the Output_Num by Integer_Text_IO.Put(A,
WIDTH_NUM, THE_BASE)
            -- as Jeffrey Carter comments then won't be any
dupplications.
            Text_IO.Put(", ");
            Output_Num(B, WIDTH_NUM, THE_BASE);
            Text_IO.Put(", ");
            Output_Num(C, WIDTH_NUM, THE_BASE);
            Text_IO.Put("  --");

			   if (A >= B) then
			   	if (A >= C) then

			   		First := A;
			   		if (B >= C) then

			   			-- First := A;
			   			Secon := B;
			   			Third := C;
			   		else

			   			-- First := A;
			   			Secon := C;
			   			Third := B;
			   		end if;
			   	else  -- C > A >= B

			   		First := C;
			   		Secon := A;
			   		Third := B;
			   	end if;
		   	elsif (B >= A) then
		   		if (B >= C) then
		   			First := B;
		   			if (A >= C) then

						-- First := B;
		   				Secon := A;
		   				Third := C;
		   			else

		   				-- First := B;
		   				Secon := C;
		   				Third := A;
		   			end if;
		   		else -- C > B >= A

		   			First := C;
		   			Secon := B;
		   			Third := A;
		   		end if;
		   	end if;

            Output_Num (First, WIDTH_NUM, THE_BASE);
            Text_IO.Put(", ");
            Output_Num (Secon, WIDTH_NUM, THE_BASE);
            Text_IO.Put(", ");
            Output_Num (Third, One_Ten'Width, 10);
            Text_IO.New_Line;

      	end Main_Process;
	end loop;
end Sort_3_Numbers;



^ permalink raw reply	[relevance 5%]

* Re: My first solution
  @ 2011-06-15  6:39  4% ` Ludovic Brenta
  0 siblings, 0 replies; 200+ results
From: Ludovic Brenta @ 2011-06-15  6:39 UTC (permalink / raw)


juanmiuk <juanmiuk@googlemail.com> writes:
> with Ada.Strings.Fixed;
> use  Ada.Strings.Fixed;
>
> procedure Test_2 is
>
>      subtype My_Num is Integer range 1 .. 10;
>
>      function Format_Num ( Width_Num  : Integer;
>                                        The_Number : Integer ) return
> String is

OK, now you can create a procedure with 3 integer parameters that writes
all 3 parameters to the console.  Inside this procedure, you can use

procedure Ada.Integer_Text_IO.Put(Item  : in Num;
                                  Width : in Field := Default_Width;
                                  Base  : in Number_Base := Default_Base);

defined in A.10.8(11).

-- 
Ludovic Brenta.



^ permalink raw reply	[relevance 4%]

* Interesting and possible buggy behavior in GNAT regarding Annex E pragmas.
@ 2011-05-25 14:54  3% Shark8
  0 siblings, 0 replies; 200+ results
From: Shark8 @ 2011-05-25 14:54 UTC (permalink / raw)


Hi everyone.
I was experimenting with partitioning-pragmas trying to decide on a
good way to set up my PostScript interpreter so that the parser could
be a remote object possibly servicing multiple clients and I came
across a possible bug that is bothering me. In certain instances using
one of the pragmas will cause the compiler to error-out, as is
expected, but in other cases the compiler does not error out.

The only way I can see this happening is if, by WITH-ing these
children units, the parent units are LIMITED WITH-ed; but that is
counter-intuitive and does not allow for USES (which still compile) of
the parent unit.

I have reduced things to the minimal compilable example and the source
is as follows:

---------------------- Example_1
With Ada.Tags;
Package Example_1 is
   -- Simple package spec which has a Stub function using the
Ada.Tags.Tag-type
   -- in a parameter; compiles.

   Procedure Stub( This_Tag : In Ada.Tags.Tag );

End Example_1;

---------------------- Example_2
With Ada.Tags;
Package Example_2 is
   -- Simple package spec which has a Stub function using the
Ada.Tags.Tag-type
   -- in a parameter and the Pragma Remote_Types has been added;
   --	THIS DOES NOT COMPILE
   --	example_2.ads:1:06: cannot depend on "Tags" (wrong
categorization)


   Pragma Remote_Types;

   Procedure Stub( This_Tag : In Ada.Tags.Tag );

End Example_2;

---------------------- Example_3
With Ada.Tags.Generic_Dispatching_Constructor;
--Use Ada.Tags; -- Uncomment this line and it STILL compiles...
Package Example_3 is
   -- Simple package spec which has a Stub function using the
Ada.Tags.Tag-type
   -- in a parameter and the Pragma Remote_Types has been added; but
the WITH
   -- for that tipe is implicit in the WITH-ing of the Dispatching
Constructor.
   --	THIS DOES NOT COMPILE
   --	example_2.ads:1:06: cannot depend on "Tags" (wrong
categorization)


   Pragma Remote_Types;

   Procedure Stub( This_Tag : In Ada.Tags.Tag );

End Example_3;

---------------------- Example Bodies
With Ada.Text_IO;

Package Body Example_# is
   -- Simple package body which has a Stub function using the
Ada.Tags.Tag-type
   -- in a parameter; this is the same (excepting the name) for all
examples.

   Procedure Stub( This_Tag : In Ada.Tags.Tag ) is
      S : String:= Ada.Tags.External_Tag( This_Tag );
   begin
      Ada.Text_IO.Put_Line( S );
   end Stub;

End Example_#;

---------------------- Experiment.adb

With
Ada.Text_IO,
     Example_1,      -- This compiles, there is nothing special about
it
--     Example_2,    -- This does not compile, as expected, the
Categorization is wrong
     Example_3       -- This *DOES* compile though...
;

with ada.Integer_Text_IO;
Procedure Experiment is

   Use Ada.Text_IO;
Begin

   Put_Line( "Terminating." );

End Experiment;



^ permalink raw reply	[relevance 3%]

* Re: index check failure - constraint error
  @ 2011-04-01 11:27  6%   ` Alex Mentis
  0 siblings, 0 replies; 200+ results
From: Alex Mentis @ 2011-04-01 11:27 UTC (permalink / raw)


tonyg wrote:

> On Apr 1, 11:53�am, tonyg <tonytheg...@gmail.com> wrote:
> > I'm getting a constraint error and I cannot see why...
> > 
> > � �function String_To_Integer (The_String : String) return Integer
> > is � � � String_Length : Integer := The_String'length;
> > � � � Return_Value : Integer := 0;
> > � � � subtype Number_Character �is character range '0'..'9';
> > � �begin
> > � � � � Int_Io.Put(String_Length);
> > � � � Ada.Text_IO.Put_Line (The_String);
> > � � � if String_Length > 0 then
> > � � � for count in 1..String_Length loop
> > � � � � �case The_String(count) is
> > � � � � � � when Number_Character =>
> > � � � � � � � �Return_Value := Return_Value +
> > � � � � � � � � �((Character'pos(The_String(count)) - 48) *
> > (10**(count-1)));
> > � � � � � � when others =>
> > � � � � � � � �raise Conversion_Error_Exception;
> > � � � � �end case;
> > � � � � �end loop;
> > � � � else
> > � � � � �Return_Value := 0;
> > � � � end if;
> > 
> > � � � return Return_Value;
> > 
> > � �end String_To_Integer;
> > 
> > I checked to see there was a string going in and it had a length.
> > The actual error was 'index check failure' but as far as I can see
> > everything is present and correct. Can anyone see what it is ?
> 
> The index check failure occurred at
> 
>   case The_String(count) is
> 
> btw


Any particular reason you aren't using the Ada-provided Get procedure
that converts a String to an Integer? It operates just like the usual
Get procedure, consuming all Integer-valid characters and stopping when
it gets to a non-digit, but you can make it detect and throw your
constraint with something like this:

with Ada.Text_Io, Ada.Integer_Text_Io;
use  Ada.Text_Io;

Procedure Main is
   
   Conversion_Error_Exception : exception;   
   
   Input1 : String := "123";
   Input2 : String := "1E3";
   Input3 : String := "12ab3";
   My_Int : Integer;
   Length : Positive;
   
begin
      
   Ada.Integer_Text_Io.Get (Input1, My_Int, Length);
   if Length /= Input1'Length then
      raise Conversion_Error_Exception;
   else
      Ada.Integer_Text_Io.Put (My_Int, 0);
      New_Line;
   end if;
   
   Ada.Integer_Text_Io.Get (Input2, My_Int, Length);
   if Length /= Input2'Length then
      raise Conversion_Error_Exception;
   else
      Ada.Integer_Text_Io.Put (My_Int, 0);
      New_Line;
   end if;
   
   Ada.Integer_Text_Io.Get (Input3, My_Int, Length);
   if Length /= Input3'Length then
      raise Conversion_Error_Exception;
   else
      Ada.Integer_Text_Io.Put (My_Int, 0);
      New_Line;
   end if;   
   
end Main;



^ permalink raw reply	[relevance 6%]

* Re: ada question
  @ 2011-04-01  1:33  5% ` Nasser M. Abbasi
  0 siblings, 0 replies; 200+ results
From: Nasser M. Abbasi @ 2011-04-01  1:33 UTC (permalink / raw)


On 3/31/2011 4:40 PM, Robin wrote:
> how can you output an integer in ada without trailing new lines? it is
> kinda hard to figure out. HEy thanks and fix probs.

Do you mean the extra space BEFORE the integer?

I did small example, and do not see an extra newline, but
see extra space only.

-------------------
with ada.text_io; use ada.text_io;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure t is
A: constant array (1..4) of integer  :=(2,3,4,5);
begin
   for i in A'range loop
       put(integer'image(A(i)));
       new_line;
   end loop;

   for i in A'range loop
       put(A(i));
       new_line;
   end loop;
end t;
---------------------------

When I run the above, I get:
---------------------------
  2
  3
  4
  5
           2
           3
           4
           5
$
-----------------------

Is this what you mean?

--Nasser



^ permalink raw reply	[relevance 5%]

* Re: Anyone see a problem in 5.7 ncurses Ada?
  @ 2011-03-09 20:28  4% ` Emile8
  0 siblings, 0 replies; 200+ results
From: Emile8 @ 2011-03-09 20:28 UTC (permalink / raw)


On 9 mar, 19:55, localh...@example.org wrote:
> I had built some programs against an earlier version of ncurses, I can't
> remember whether it was 5.5 or later and they were working fine. When I
> rebuilt them against 5.7 a few of them broke. I have tracked it down to
> incorrect values being returned by get_size. For a 24x80 xterm get_size is
> returning 25 columns and 81 lines. This makes the values actually 2 higher
> than they should be, because the numbers are supposed to be
> zero-relative. That is the lines should be 23 and the columns 79. Has anyone
> else noticed this? I don't know whether it's in the Ada binding or in
> ncurses itself. I would think if ncurses itself was broken people would have
> noted and fixed it but then again I don't think the Ada binding has been
> touched in years (and wow, it's good).

I confirm your observation on the Ada binding of the version 5.7 of
ncurses. The numbers of lines and columns are 1 higher than the actual
ones. I don't know if this is relevant but Get_Size gives the number
of lines and columns of a window in the terminal. It seems so that the
standard_window is a bit greater than its terminal.

with Terminal_Interface.Curses; use Terminal_Interface.Curses;
with ncurses2.util;             use ncurses2.util;
with ada.text_io; use ada.text_io;
with Ada.integer_Text_IO; use Ada.integer_Text_IO;

procedure test1 is
   NL : Line_count;
   NC : Column_count;
begin
   init_screen;
   Get_size (number_of_columns => NC, number_of_lines => NL);
   put(integer(NL));
   put_line("");
   put(integer(NC));
   delay 10.0;
end test1;


Here after is the source code of Get_Size. It could be that the
problem comes from the value of Offset_XY.

procedure Get_Size
     (Win               : in Window := Standard_Window;
      Number_Of_Lines   : out Line_Count;
      Number_Of_Columns : out Column_Count)
   is
      function GetMaxY (W : Window) return C_Int;
      pragma Import (C, GetMaxY, "getmaxy");

      function GetMaxX (W : Window) return C_Int;
      pragma Import (C, GetMaxX, "getmaxx");

      Y : constant C_Int := GetMaxY (Win)
                          + C_Int (Offset_XY);
      X : constant C_Int := GetMaxX (Win)
                          + C_Int (Offset_XY);
   begin
      Number_Of_Lines   := Line_Count (Y);
      Number_Of_Columns := Column_Count (X);
   end Get_Size;



^ permalink raw reply	[relevance 4%]

* Re: Need some light on using Ada or not
  2011-02-20 19:54  4%     ` Brian Drummond
@ 2011-02-23 22:19  0%       ` Luis P. Mendes
  0 siblings, 0 replies; 200+ results
From: Luis P. Mendes @ 2011-02-23 22:19 UTC (permalink / raw)


Sun, 20 Feb 2011 19:54:30 +0000, Brian Drummond escreveu:

> On 20 Feb 2011 00:20:56 GMT, "Luis P. Mendes" <luislupeXXX@gmailXXX.com>
> wrote:
> 
>>Sat, 19 Feb 2011 13:07:58 +0000, Brian Drummond escreveu:
>> 
>>> Ada can easily bind to C libraries, it's standard and well documented.
> 
>>> C++ bindings are also possible, but with some work and (currently)
>>> some limitations.
>>> A GCC recent enough to support "-f-dump-ada-spec" will auto-generate
>>> an Ada spec from C++ sources, which will save a lot of the work.
>>
>>Would you mind giving me an example?
> 
> See below...
> 
>>Please consider the following C++ code: ===== header file
>>$ cat aleatorio.h
> 
>>===== source file
>>$ cat aleatorio.cpp
> 
>>=====
>>
>>From Ada, how can I use these h and cpp files to call, for example,
>>gerarAleatorioInteiro(0,10)?
> 
> Here is what I did.
> 
> 1)  Comment out the #includes in aleatorio.h. They are unused; enlarge
> the namespace; and are repeated in the .cpp file anyway.
> 
> Save it as aleatorio.hpp. (This forces C++-style Ada specs rather than
> C-style, which is essential to link to C++ code)
> 
> 2) Generate the specs automatically.
> /usr/gnat/bin/gcc -fdump-ada-spec aleatorio.hpp produces an automatic
> spec file
> aleatorio_hpp.ads
> -------------------------------
> with Interfaces.C; use Interfaces.C;
> 
> package aleatorio_hpp is
> 
>    procedure iniciarSemente;  -- aleatorio.hpp:8:21 pragma Import (CPP,
>    iniciarSemente, "_Z14iniciarSementev");
> 
>    function gerarAleatorio (a : int; b : int) return double;
> 	-- aleatorio.hpp:9:35
>    pragma Import (CPP, gerarAleatorio, "_Z14gerarAleatorioii");
> 
>    function gerarAleatorioInteiro (a : int; b : int) return int;
> 	-- aleatorio.hpp:10:39
>    pragma Import (CPP, gerarAleatorioInteiro,
>    "_Z21gerarAleatorioInteiroii");
> 
>    function arredondar (res : double) return int;
> 	-- aleatorio.hpp:11:26
>    pragma Import (CPP, arredondar, "_Z10arredondard");
> 
> end aleatorio_hpp;
> -------------------------------
> 
> 3) Not essential but recommended ...
> 
> Write a wrapper package to hide the C interface and C types, and to make
> the interface look like Ada: random_wrapper.ads, random_wrapper.adb.
> (This constitutes a "thick binding", while package aleatorio_h is a
> "thin binding")
> At this point you can choose what to expose to the Ada code; I have been
> selective (or lazy!)
> 
> ------------ random_wrapper.ads -------------- package random_wrapper is
>  
>    procedure initialise_seed;
>    function random_between(a,b : in Integer) return Integer;
>   
> end random_wrapper;
> ------------ random_wrapper.adb -------------- with aleatorio_hpp;
> use aleatorio_hpp;
> with Interfaces.C;
> use Interfaces.C;
> 
> package body random_wrapper is
> 
>    procedure initialise_seed is
>    begin
>       iniciarSemente;
>    end initialise_seed;
> 
>    function random_between(a,b : in Integer) return Integer is begin
>       return Integer(gerarAleatorioInteiro (int(a), int(b)));
>    end random_between;
> 
> end random_wrapper;
> ----------------------------------------------
> 
> 4)  Write your Ada program...
> ------------ random.adb ---------------------- --Random number tester
> 
> with Ada.Text_Io; 		use Ada.Text_Io;
> with Ada.Integer_Text_Io; 	use Ada.Integer_Text_Io; with 
random_wrapper;
> 	use random_wrapper;
> 
> procedure random is
> 
> begin
>    initialise_seed;
>    Put("Five random numbers");
>    New_Line;
>    for i in 1 .. 5 loop
>       Put(random_between(1,100));
>       New_Line;
>    end loop;
> end random;
> ----------------------------------------------
> 
> 5) Compile the C++ portion (more complex examples may need a Makefile)
> 
> g++ -g -m64 -c -o aleatorio.o aleatorio.cpp
> 
> 6) Build the Ada portion.
> 
> gnatmake -m64 -gnat05 -gnato -gnatwa -fstack-check -o random random.adb
> \
> 	-largs ./aleatorio.o -lstdc++
> 
> Note additional arguments "-largs ./aleatorio.o -lstdc++" to gnatlink;
> extend these if you add more C++ objects and libraries.
> 
> 7)
> Run it.
> 
> ./random
> Five random numbers
>           9
>          40
>           2
>          77
>          66

Thank you very much Brian!

I guess that this example or another one like this could be included in 
wiki or other place for newcomers.


Luis



^ permalink raw reply	[relevance 0%]

* Re: Need some light on using Ada or not
  2011-02-21 12:52  3%                 ` Brian Drummond
  2011-02-21 13:44  3%                   ` Simon Wright
@ 2011-02-22  2:15  1%                   ` Shark8
  1 sibling, 0 replies; 200+ results
From: Shark8 @ 2011-02-22  2:15 UTC (permalink / raw)


On Feb 21, 4:52 am, Brian Drummond <brian_drumm...@btconnect.com>
wrote:
>
> As this is my first experiment with tasking, comments are welcome (and I'd be
> interested to see your version). If people think this is worth submitting to the
> shootout, I'll go ahead.
>
> - Brian

I used arrays for the most part, and then expanded it out to a
recursive-definition for the trees which would be too large for
the stack during creation.

It may be going against the spirit of the competition, but nothing
there said that we couldn't use arrays as binary-trees.


-- Package B_Tree
-- by Joey Fish

Package B_Tree is


   -- Contest rules state:
   --	define a tree node class and methods, a tree node record and
procedures,
   --	or an algebraic data type and functions.
   --
   -- B_Tree is the definition of such a record and procedures.

   Type Binary_Tree is Private;

   Function  Build_Tree	(Item : Integer; Depth : Natural)    Return
Binary_Tree;
   Function  Subtree	(Tree : Binary_Tree; Left : Boolean) Return
Binary_Tree;
   Function  Item_Check	(This : Binary_Tree)		     Return Integer;
   Procedure Free	(Tree : In Out Binary_Tree);

Private

   Type Node_Data;
   Type Data_Access		is Access Node_Data;
   SubType Not_Null_Data_Access	is Not Null Data_Access;

   Function Empty Return Not_Null_Data_Access;
   Type Binary_Tree( Extension : Boolean:= False ) is Record
      Data   :  Not_Null_Data_Access:= Empty;
   End Record;

End B_Tree;

--- B_Trees body
with
Ada.Text_IO,
--Ada.Numerics.Generic_Elementary_Functions,
Unchecked_Deallocation;

Package Body B_Tree is

   -- In some cases the allocataion of the array is too large, so we
can split
   -- that off into another tree, for that we have Tree_Array, which
is a
   -- Boolean-indexed array. {The Index is also shorthand for Is_left
on such.}
   Type Tree_Array	is Array (Boolean) of Binary_Tree;

   -- For trees of up to 2**17 items we store the nodes as a simple
array.
   Type Integer_Array	is Array (Positive Range <>) of Integer;
   Type Access_Integers	is Access Integer_Array;
   Type Node_Data(Extended : Boolean:= False) is Record
      Case Extended is
         When False => A : Not Null Access_Integers;
         When True  => B : Tree_Array;
      end Case;
   End Record;


   --  Returns the Empty List's Data.
   Function Empty Return Not_Null_Data_Access is
   begin
      Return New Node_Data'( A => New Integer_Array'(2..1 => 0),
Others => <> );
   end Empty;



      -- We'll need an integer-version of logrithm in base-2
      Function lg( X : In Positive ) Return Natural is
         --------------------------------------------
         --  Base-2 Log with a jump-table for the  --
         --  range 1..2**17-1 and a recursive call --
         --  for all values greater.		   --
         --------------------------------------------
      begin
         Case X Is
            When 2**00..2**01-1	=> Return  0;
            When 2**01..2**02-1	=> Return  1;
            When 2**02..2**03-1	=> Return  2;
            When 2**03..2**04-1	=> Return  3;
            When 2**04..2**05-1	=> Return  4;
            When 2**05..2**06-1	=> Return  5;
            When 2**06..2**07-1	=> Return  6;
            When 2**07..2**08-1	=> Return  7;
            When 2**08..2**09-1	=> Return  8;
            When 2**09..2**10-1	=> Return  9;
            When 2**10..2**11-1	=> Return 10;
            When 2**11..2**12-1	=> Return 11;
            When 2**12..2**13-1	=> Return 12;
            When 2**13..2**14-1	=> Return 13;
            When 2**14..2**15-1	=> Return 14;
            When 2**15..2**16-1	=> Return 15;
            When 2**16..2**17-1	=> Return 16;
            When Others		=> Return 16 + lg( X / 2**16 );
         End Case;
      end lg;

   Function Build_Tree (Item : Integer; Depth : Natural) Return
Binary_Tree is
      -- Now we need a function to allow the calculation of a node's
value
      -- given that node's index.
      Function Value( Index : Positive ) Return Integer is
	Level : Integer:= lg( Index );
	-- Note: That is the same as
	--	Integer( Float'Truncation( Log( Float(Index),2.0 ) ) );
	-- but without the Integer -> Float & Float -> Integer conversions.
      begin
         Return (-2**(1+Level)) + 1 + Index;
      end;

   Begin
      If Depth < 17 then
         Return Result : Binary_Tree do
            Result.Data:= New Node_Data'
		( A => New Integer_Array'(1..2**Depth-1 => <>), Others => <> );
            For Index in Result.Data.A.All'Range Loop
		Result.Data.All.A.All( Index ):= Value(Index) + Item;
            End Loop;
         End Return;
      else
         Return Result : Binary_Tree do
            Result.Data:= New Node_Data'
              ( B =>
                (True => Build_Tree(-1,Depth-1), False =>
Build_Tree(0,Depth-1)),
               Extended => True );
         End Return;

      end if;
   End Build_Tree;

   Function Subtree (Tree : Binary_Tree; Left : Boolean) Return
Binary_Tree is
   Begin
      if Tree.Data.Extended then
         -- If it is a large enough tree, then we already have it
split.
         Return Tree.Data.B(Left);
      else
         -- If not then we just need to calculate the middle and
return the
         -- proper half [excluding the first (root) node.
         Declare
            Data	  : Integer_Array Renames Tree.Data.All.A.All;
            Data_Length : Natural:= Data'Length;

            Mid_Point : Positive:= (Data_Length/2) + 1;
            SubType LeftTree is Positive Range
              Positive'Succ(1)..Mid_Point;
            SubType RightTree is Positive Range
              Positive'Succ(Mid_Point)..Data_Length;
         Begin
            Return Result : Binary_Tree Do
               if Left then
                  Result.Data:= New Node_Data'
                    ( A => New Integer_Array'( Data(LeftTree)  ),
Others => <> );
               else
                  Result.Data:= New Node_Data'
                    ( A => New Integer_Array'( Data(RightTree) ),
Others => <> );
               end if;
            End Return;
         End;
      end if;
   End Subtree;

   Function Check_Sum(	Data: In Integer_Array	) Return Integer is
      Depth : Natural:= lg(Data'Length);
      SubType Internal_Nodes is Positive Range 1..2**Depth-1;
   begin
      Return Result : Integer:= 0 do
         For Index in Internal_Nodes Loop
            Declare
               Left	: Positive:= 2*Index;
               Right	: Positive:= Left+1;
            Begin
               If Index mod 2 = 1 then
                  Result:= Result - Right + Left;
               else
                  Result:= Result + Right - Left;
               end if;
            End;
         End Loop;
      End Return;
   end Check_Sum;

   Function Item_Check	(This : Binary_Tree) Return Integer is
      -- For large trees this function calls itself recursively until
the
      -- smaller format is encountered; otherwise, for small trees, it
acts as
      -- a pass-througn to Check_Sum.
   Begin
      If This.Data.Extended then
         Declare

         Begin
            Return Result: Integer:= -1 do
               Result:=   Result
			+ Item_Check( This.Data.B(False) )
			- Item_Check( This.Data.B(True ) );
            End Return;
         End;
      else
         Declare
            Data : Integer_Array Renames This.Data.All.A.All;
         Begin
            Return Check_Sum( Data );
         End;
      end if;
   End Item_Check;

   Procedure Free	(Tree : In Out Binary_Tree) is
      procedure Deallocate is new
		Unchecked_Deallocation(Integer_Array, Access_Integers);
      procedure Deallocate is new
		Unchecked_Deallocation(Node_Data, Data_Access);

      Procedure Recursive_Free	(Tree : In Out Binary_Tree) is
      begin
         if Tree.Data.All.Extended then
            Recursive_Free( Tree.Data.B(True ) );
            Recursive_Free( Tree.Data.B(False) );
            Declare
               Data : Data_Access;
               For Data'Address Use Tree.Data'Address;
               Pragma Import( Ada, Data );
            Begin
               Deallocate(Data);
            End;
         else
            Declare
               Data : Data_Access;
               For Data'Address Use Tree.Data.All.A'Address;
               Pragma Import( Ada, Data );
            Begin
               Deallocate( Data );
               Data:= Empty;
            End;
         end if;
      end Recursive_Free;

   begin
      Recursive_Free( Tree );
      Tree.Data:= Empty;
   end Free;

Begin
   Null;
End B_Tree;

-- BinaryTrees.adb
-- by Jim Rogers
-- modified by Joey Fish

With
B_Tree,
Ada.Text_Io,
Ada.Real_Time,
Ada.Command_Line,
Ada.Characters.Latin_1,
;

Use
B_Tree,
Ada.Text_Io,
Ada.Command_Line,
Ada.Integer_Text_Io,
Ada.Characters.Latin_1
;

procedure BinaryTrees is
   --Depths
   Min_Depth	: Constant Positive := 4;
   Max_Depth	: Positive;
   Stretch_Depth: Positive;
   N		: Natural := 1;

   -- Trees
   Stretch_Tree,
   Long_Lived_Tree	: Binary_Tree;


   Check,
   Sum		: Integer;
   Depth	: Natural;
   Iterations	: Positive;

   Package Fn is New
Ada.Numerics.Generic_Elementary_Functions( Float );
   Function Value( Index : Positive ) Return Integer is
      Level : Integer:=
	Integer( Float'Truncation( Fn.Log( Float(Index),2.0 ) ) );
   begin
      Return (-2**(1+Level)) + 1 + Index;
   end;


begin
--     For Index in 1..2**3-1 loop
--        Put_Line( Value(Index)'img );
--     end loop;

--     Declare
--        -- allocate new memory:
--        Short_Lived_Tree_1: Binary_Tree:= Build_Tree(0, 20);
--     Begin
--        Sum:= Item_Check (Short_Lived_Tree_1);
--  --        Check := Check + Sum;
--  --        Free( Short_Lived_Tree_1 );
--        Put(Check'Img);
--     End;


   if Argument_Count > 0 then
      N := Positive'Value(Argument(1));
   end if;
   Max_Depth := Positive'Max(Min_Depth + 2, N);
   Stretch_Depth := Max_Depth + 1;
   Stretch_Tree := Build_Tree(0, Stretch_Depth);
   Check:= Item_Check(Stretch_Tree);
   Put("stretch tree of depth ");
   Put(Item => Stretch_Depth, Width => 1);
   Put(Ht & " check: ");
   Put(Item => Check, Width => 1);
   New_Line;

   Long_Lived_Tree := Build_Tree(0, Max_Depth);

   Depth := Min_Depth;
   while Depth <= Max_Depth loop
      Iterations := 2**(Max_Depth - Depth + Min_Depth);
      Check := 0;
      for I in 1..Iterations loop
         Declare
            Short_Lived_Tree_1: Binary_Tree:= Build_Tree(I, Depth);
         Begin
            Sum:= Item_Check (Short_Lived_Tree_1);
            Check := Check + Sum;
            Free( Short_Lived_Tree_1 );
         End;


         Declare
            Short_Lived_Tree_2: Binary_Tree:= Build_Tree(-I, Depth);
         Begin
            Sum:= Item_Check (Short_Lived_Tree_2);
            Check := Check + Sum;
            Free( Short_Lived_Tree_2 );
         End;
      end loop;

      Put(Item => Iterations * 2, Width => 0);
      Put(Ht & " trees of depth ");
      Put(Item => Depth, Width => 0);
      Put(Ht & " check: ");
      Put(Item => Check, Width => 0);
      New_Line;
      Depth := Depth + 2;
   end loop;
   Put("long lived tree of depth ");
   Put(Item => Max_Depth, Width => 0);
   Put(Ht & " check: ");
   check:= Item_Check(Long_Lived_Tree);
   Put(Item => Check, Width => 0);
   New_Line;

end BinaryTrees;




^ permalink raw reply	[relevance 1%]

* Re: Need some light on using Ada or not
  2011-02-21 12:52  3%                 ` Brian Drummond
@ 2011-02-21 13:44  3%                   ` Simon Wright
  2011-02-22  2:15  1%                   ` Shark8
  1 sibling, 0 replies; 200+ results
From: Simon Wright @ 2011-02-21 13:44 UTC (permalink / raw)


[-- Attachment #1: Type: text/plain, Size: 367 bytes --]

Brian Drummond <brian_drummond@btconnect.com> writes:

> As this is my first experiment with tasking, comments are welcome (and
> I'd be interested to see your version).

See end.

> If people think this is worth submitting to the shootout, I'll go
> ahead.

I think it definitely is: the only Ada code for binary-trees is
single-threaded, so looks needlessly poor.


[-- Attachment #2: simple multi-thread version of binary trees benchmark --]
[-- Type: text/plain, Size: 5283 bytes --]

----------------------------------------------------------------
-- BinaryTrees
--
-- Ada 95 (GNAT)
--
-- Contributed by Jim Rogers
-- Modified by Simon Wright
----------------------------------------------------------------
with Tree_Nodes; use Tree_Nodes;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with System;

procedure Binarytrees is
   Min_Depth : constant Positive := 4;
   N : Natural := 1;
   Stretch_Tree : Tree_Node;
   Long_Lived_Tree : Tree_Node;
   Max_Depth : Positive;
   Stretch_Depth : Positive;

   task type Check_Tree is
      pragma Priority (System.Default_Priority - 1);
      entry Start (Iterations : Positive; Depth : Positive);
      entry Sum (Result : out Integer);
   end Check_Tree;

   task body Check_Tree is
      Iterations : Positive;
      Depth : Positive;
      Tree : Tree_Node;
      Check : Integer := 0;
   begin
      accept Start (Iterations : Positive; Depth : Positive) do
         Check_Tree.Iterations := Iterations;
         Check_Tree.Depth := Depth;
      end Start;
      for J in 1 .. Iterations loop
         Tree := Bottom_Up_Tree (J, Depth);
         Check := Check + Item_Check (Tree);
         Delete_Tree (Tree);
         Tree := Bottom_Up_Tree (-J, Depth);
         Check := Check + Item_Check (Tree);
         Delete_Tree (Tree);
      end loop;
      accept Sum (Result : out Integer) do
         Result := Check;
      end Sum;
   end Check_Tree;

begin

   if Argument_Count > 0 then
      N := Positive'Value (Argument (1));
   end if;

   Max_Depth := Positive'Max (Min_Depth + 2, N);
   Stretch_Depth := Max_Depth + 1;

   Stretch_Tree := Bottom_Up_Tree (0, Stretch_Depth);
   Put ("stretch tree of depth ");
   Put (Item => Stretch_Depth, Width => 1);
   Put (Ht & " check: ");
   Put (Item => Item_Check (Stretch_Tree), Width => 1);
   New_Line;
   Delete_Tree (Stretch_Tree);

   Long_Lived_Tree := Bottom_Up_Tree (0, Max_Depth);

   declare
      subtype Check_Trees_Array_Range
      is Natural range 0 .. (Max_Depth - Min_Depth) / 2;
      Check_Trees : array (Check_Trees_Array_Range) of Check_Tree;
      function Depth (For_Entry : Check_Trees_Array_Range) return Natural
      is
      begin
         return For_Entry  * 2 + Min_Depth;
      end Depth;
      function Iterations (For_Entry : Check_Trees_Array_Range) return Positive
      is
      begin
         return 2 ** (Max_Depth - Depth (For_Entry) + Min_Depth);
      end Iterations;
   begin
      for D in Check_Trees'Range loop
         Check_Trees (D).Start (Iterations => Iterations (D),
                                Depth => Depth (D));
      end loop;
      for D in Check_Trees'Range loop
         Put (Item => Iterations (D) * 2, Width => 0);
         Put (Ht & " trees of depth ");
         Put (Item => Depth (D), Width => 0);
         declare
            Check : Integer;
         begin
            Check_Trees (D).Sum (Result => Check);
            Put (Ht & " check: ");
            Put (Item => Check, Width => 0);
         end;
         New_Line;
      end loop;
   end;

   Put ("long lived tree of depth ");
   Put (Item => Max_Depth, Width => 0);
   Put (Ht & " check: ");
   Put (Item => Item_Check (Long_Lived_Tree), Width => 0);
   New_Line;
   Delete_Tree (Long_Lived_Tree);

end BinaryTrees;
----------------------------------------------------------------
-- BinaryTrees
--
-- Ada 95 (GNAT)
--
-- Contributed by Jim Rogers
-- Modified by Simon Wright
----------------------------------------------------------------

with Ada.Unchecked_Deallocation;

package body Tree_Nodes is

   function Bottom_Up_Tree (Item : Integer; Depth : Natural) return Tree_Node
   is
   begin
      if Depth > 0 then
         return new Node'(Bottom_Up_Tree (2 * Item - 1, Depth - 1),
                          Bottom_Up_Tree (2 * Item, Depth - 1),
                          Item);
      else
         return new Node'(null, null, Item);
      end if;
   end Bottom_Up_Tree;

   function Item_Check (This : Tree_Node) return Integer
   is
   begin
      if This.Left = null then
         return This.Item;
      else
         return This.Item + Item_Check (This.Left) - Item_Check (This.Right);
      end if;
   end Item_Check;

   procedure Delete_Tree (This : in out Tree_Node)
   is
      procedure Free is new Ada.Unchecked_Deallocation (Node, Tree_Node);
   begin
      if This /= null then
         Delete_Tree (This.Left);
         Delete_Tree (This.Right);
         Free (This);
      end if;
   end Delete_Tree;

end Tree_Nodes;
----------------------------------------------------------------
-- BinaryTrees
--
-- Ada 95 (GNAT)
--
-- Contributed by Jim Rogers
-- Modified by Simon Wright
----------------------------------------------------------------

package Tree_Nodes is
   type Tree_Node is private;
   function Bottom_Up_Tree (Item : Integer; Depth : Natural) return Tree_Node;
   function Item_Check (This : Tree_Node) return Integer;
   procedure Delete_Tree (This : in out Tree_Node);
private
   type Node;
   type Tree_Node is access Node;
   type Node is record
      Left  : Tree_Node;
      Right : Tree_Node;
      Item  : Integer := 0;
   end record;
end Tree_Nodes;

^ permalink raw reply	[relevance 3%]

* Re: Need some light on using Ada or not
  @ 2011-02-21 12:52  3%                 ` Brian Drummond
  2011-02-21 13:44  3%                   ` Simon Wright
  2011-02-22  2:15  1%                   ` Shark8
  0 siblings, 2 replies; 200+ results
From: Brian Drummond @ 2011-02-21 12:52 UTC (permalink / raw)


On Sun, 20 Feb 2011 22:47:05 +0000, Simon Wright <simon@pushface.org> wrote:

>Brian Drummond <brian_drummond@btconnect.com> writes:
>
>> the 100% overhead (on this test case) imposed by the pthread library
>> (which I think is how Gnat implements its tasking)
>
>Here (Mac OS X, GCC 4.6.0 x86_64 experimental), I tried modifying the
>Ada code to use the same tasking (threading) structure as the C GNU GCC
>#5 version. Result (I only checked with parameter 16):
>
>C:           real 5.1 user 9.0
>GNAT (orig): real 6.0 user 5.8
>GNAT (mod):  real 5.3 user 9.4
>
>(the 'user' value, which is what time(1) reports, is apparently the
>total CPU time, while the 'real' time is the elapsed time; this machine
>has 2 cores, both it seems running at about 90% in the test).

So again, there is an overhead (maybe 80%) imposed by tasking, and significant
improvements won't appear until >2 processors.

I can't be sure I'm reading the C correctly, but it looks as if it's creating a
new pthread (task) for each depth step, similar to my first attempt.

I have now decoupled the number of tasks from the problem, to simplify
experiments with different numbers of tasks, and improve load balancing.
It runs approx. 4x as fast with 4 or 8 tasks as it does with 1 task (on a 4-core
machine!), therefore only about 2x as fast as it does without tasking.

As this is my first experiment with tasking, comments are welcome (and I'd be
interested to see your version). If people think this is worth submitting to the
shootout, I'll go ahead.

- Brian

----------------------------------------------------------------
-- BinaryTrees
--
-- Ada 95 (GNAT)
--
-- Contributed by Jim Rogers
-- Tasking experiment : Brian Drummond
----------------------------------------------------------------
with Treenodes; use Treenodes;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;

procedure Binarytrees_tasking is
   -- Change "CPUs" to control number of tasks created
   CPUs : constant Positive := 8;
   BlockSize : Positive;
   Min_Depth : constant Positive := 4;
   N : Natural := 1;
   Stretch_Tree : TreeNode;
   Long_Lived_Tree : TreeNode;
   Max_Depth : Positive;
   Stretch_Depth : Positive;
   Iteration : Positive;
   Iterations : Positive;
   Sum : Integer;
   Check : Integer;
   Depth : Natural;

   task type check_this_depth is
      entry Start(Iteration, Size : Positive; To_Depth :in Natural);
      entry Complete(Result : out Integer);
   end check_this_depth;

   task body check_this_depth is
      Check : Integer;
      Sum : Integer;
      Depth : Natural;
      First : Positive;
      Last : Positive;
      Short_Lived_Tree_1 : TreeNode;
      Short_Lived_Tree_2 : TreeNode;

   begin
      loop
         select
            accept Start(Iteration, Size : Positive; To_Depth :in Natural) do
               First := Iteration;
               Last := Iteration + Size - 1;
               Depth := To_Depth;
            end Start;
            Check := 0;
            for I in First .. Last loop
               Short_Lived_Tree_1 := Bottom_Up_Tree(Item => I, Depth => Depth);
               Short_Lived_Tree_2 := Bottom_Up_Tree(Item =>-I, Depth => Depth);
               Item_Check(Short_Lived_Tree_1, Sum);
               Check := Check + Sum;
               Item_Check(Short_Lived_Tree_2, Sum);
               Check := Check + Sum;
            end loop;
            accept Complete(Result : out Integer) do
               Result := Check;
            end Complete;
         or
            Terminate;
         end select;
      end loop;
   end check_this_depth;

   subtype Task_Count is positive range 1 .. CPUs;	
   Tasks : array (Task_Count) of check_this_depth;

begin
   if Argument_Count > 0 then
      N := Positive'Value(Argument(1));
   end if;
   Max_Depth := Positive'Max(Min_Depth + 2, N);
   Stretch_Depth := Max_Depth + 1;
   Stretch_Tree := Bottom_Up_Tree(0, Stretch_Depth);
   Item_Check(Stretch_Tree, Check);
   Put("stretch tree of depth ");
   Put(Item => Stretch_Depth, Width => 1);
   Put(Ht & " check: ");
   Put(Item => Check, Width => 1);
   New_Line;
   
   Long_Lived_Tree := Bottom_Up_Tree(0, Max_Depth);
   
   Depth := Min_Depth;
   while Depth <= Max_Depth loop
      Iterations := 2**(Max_Depth - Depth + Min_Depth);
      Check := 0;

-- Setup tasking parameters for reasonable task granularity
-- Too large and we can't balance CPU loads
-- Too small and we waste time in task switches
-- Not very critical - anything more complex is probably a waste of effort
      
      BlockSize := 2**10;
      if Iterations < BlockSize * CPUs then
         BlockSize := 1;
      end if;
  
-- Check that Iterations is a multiple of Blocksize * CPUs
-- Error out otherwise (dealing with remainder is trivial but tedious)
      Pragma Assert(Iterations mod( BlockSize * CPUs) = 0, 
                            "Iteration count not supported!");

      -- for I in 1..Iterations loop  
      Iteration := 1;   
      while Iteration <= Iterations loop
         for j in Task_Count loop
            Tasks(j).Start(Iteration, Blocksize, Depth);
            Iteration := Iteration + BlockSize;
         end loop;
         for j in Task_Count loop
            Tasks(j).Complete(Sum);
            Check := Check + Sum;
         end loop;
      end loop;
      Put(Item => Iterations * 2, Width => 0);
      Put(Ht & " trees of depth ");
      Put(Item => Depth, Width => 0);
      Put(Ht & " check: ");
      Put(Item => Check, Width => 0);
      New_Line;
      Depth := Depth + 2;
   end loop;
   Put("long lived tree of depth ");
   Put(Item => Max_Depth, Width => 0);
   Put(Ht & " check: ");
   Item_Check(Long_Lived_Tree, Check);
   Put(Item => Check, Width => 0);
   New_Line;
end BinaryTrees_tasking;




^ permalink raw reply	[relevance 3%]

* Re: Need some light on using Ada or not
  @ 2011-02-20 19:54  4%     ` Brian Drummond
  2011-02-23 22:19  0%       ` Luis P. Mendes
  0 siblings, 1 reply; 200+ results
From: Brian Drummond @ 2011-02-20 19:54 UTC (permalink / raw)


On 20 Feb 2011 00:20:56 GMT, "Luis P. Mendes" <luislupeXXX@gmailXXX.com> wrote:

>Sat, 19 Feb 2011 13:07:58 +0000, Brian Drummond escreveu:
> 
>> Ada can easily bind to C libraries, it's standard and well documented.

>> C++ bindings are also possible, but with some work and (currently) some
>> limitations.
>> A GCC recent enough to support "-f-dump-ada-spec" will auto-generate an
>> Ada spec from C++ sources, which will save a lot of the work. 
>
>Would you mind giving me an example?

See below...

>Please consider the following C++ code:
>===== header file
>$ cat aleatorio.h 

>===== source file
>$ cat aleatorio.cpp 

>=====
>
>From Ada, how can I use these h and cpp files to call, for example, 
>gerarAleatorioInteiro(0,10)?

Here is what I did.

1)  Comment out the #includes in aleatorio.h.
They are unused; enlarge the namespace; and are repeated in the .cpp file
anyway.

Save it as aleatorio.hpp. (This forces C++-style Ada specs rather than C-style,
which is essential to link to C++ code)

2) Generate the specs automatically.
/usr/gnat/bin/gcc -fdump-ada-spec aleatorio.hpp
produces an automatic spec file
aleatorio_hpp.ads
-------------------------------
with Interfaces.C; use Interfaces.C;

package aleatorio_hpp is

   procedure iniciarSemente;  -- aleatorio.hpp:8:21
   pragma Import (CPP, iniciarSemente, "_Z14iniciarSementev");

   function gerarAleatorio (a : int; b : int) return double;  
	-- aleatorio.hpp:9:35
   pragma Import (CPP, gerarAleatorio, "_Z14gerarAleatorioii");

   function gerarAleatorioInteiro (a : int; b : int) return int;  
	-- aleatorio.hpp:10:39
   pragma Import (CPP, gerarAleatorioInteiro, "_Z21gerarAleatorioInteiroii");

   function arredondar (res : double) return int;  
	-- aleatorio.hpp:11:26
   pragma Import (CPP, arredondar, "_Z10arredondard");

end aleatorio_hpp;
-------------------------------

3) Not essential but recommended ...

Write a wrapper package to hide the C interface and C types, and to make the
interface look like Ada: random_wrapper.ads, random_wrapper.adb.
(This constitutes a "thick binding", while package aleatorio_h is a "thin
binding")
At this point you can choose what to expose to the Ada code; 
I have been selective (or lazy!)

------------ random_wrapper.ads --------------
package random_wrapper is
 
   procedure initialise_seed;
   function random_between(a,b : in Integer) return Integer;
  
end random_wrapper;
------------ random_wrapper.adb --------------
with aleatorio_hpp;		
use aleatorio_hpp;
with Interfaces.C; 
use Interfaces.C;

package body random_wrapper is

   procedure initialise_seed is
   begin
      iniciarSemente;
   end initialise_seed;

   function random_between(a,b : in Integer) return Integer is
   begin
      return Integer(gerarAleatorioInteiro (int(a), int(b)));
   end random_between;

end random_wrapper;
----------------------------------------------

4)  Write your Ada program...
------------ random.adb ----------------------
--Random number tester

with Ada.Text_Io; 		use Ada.Text_Io;
with Ada.Integer_Text_Io; 	use Ada.Integer_Text_Io;
with random_wrapper;		use random_wrapper;

procedure random is

begin
   initialise_seed;
   Put("Five random numbers");
   New_Line;
   for i in 1 .. 5 loop
      Put(random_between(1,100));
      New_Line;
   end loop;
end random;
----------------------------------------------

5) Compile the C++ portion (more complex examples may need a Makefile)

g++ -g -m64 -c -o aleatorio.o aleatorio.cpp 

6) Build the Ada portion. 

gnatmake -m64 -gnat05 -gnato -gnatwa -fstack-check -o random random.adb \
	-largs ./aleatorio.o -lstdc++ 

Note additional arguments "-largs ./aleatorio.o -lstdc++" to gnatlink; 
extend these if you add more C++ objects and libraries. 

7) 
Run it.

./random
Five random numbers
          9
         40
          2
         77
         66




^ permalink raw reply	[relevance 4%]

* Re: Need some light on using Ada or not
  @ 2011-02-20 14:34  4%       ` Brian Drummond
    0 siblings, 1 reply; 200+ results
From: Brian Drummond @ 2011-02-20 14:34 UTC (permalink / raw)


On Sat, 19 Feb 2011 18:25:44 +0000, Brian Drummond
<brian_drummond@btconnect.com> wrote:

>On Sat, 19 Feb 2011 15:36:45 +0100, Georg Bauhaus
><rm-host.bauhaus@maps.futureapps.de> wrote:
>
>>On 2/19/11 2:07 PM, Brian Drummond wrote:
>>> On 18 Feb 2011 22:52:38 GMT, "Luis P. Mendes"<luislupeXXX@gmailXXX.com>  wrote:
>>
>>>> I have some questions, however, that I'd like to be answered:
>>>> 1. If Ada is more type safe and restricted than C++, how can it be
>>>> significantly slower?
>>> Two possible reasons; both come down to the relative number of people developing
>>> for both languages.

[using tasking for the binary_trees benchmark, which currently uses a single
task...]
>>I vaguely remember that it has been tried before, but so far there
>>is no better solution.

>I have broken down and finally started to learn Ada's tasking. So far I have
>gone from 56s (CPU) 56s (elapsed) with one task, to 120s (CPU), 64s(elapsed)
>with multiple tasks (on a smallish 2-core laptop)... 
>
>Disappointing.
>
>(If anybody's interested, I am using 9 tasks, one per "Depth" value in the main
>while loop. 

Further odd results. I re-structured the tasking so that I could modify the
number of tasks, from 1, 2, 4, etc. The "CPU" utilisation remains virtually
identical, at 2 minutes; the elapsed time is 2 minutes with 1 task, or 1 minute
with 2 or more (on a 2-core laptop. I'll report on a 4-core later).

Moving from GCC4.5.0 (FSF) to Adacore Libre 2010 makes no significant
difference. (OpenSuse 11.3, 64-bit, 2-core laptop)

Doubling the CPU time with a single task is suspicious, so I tried the following
experiment : source code below - main program only. For the rest, and the
original version, see
http://shootout.alioth.debian.org/u64q/performance.php?test=binarytrees

I removed virtually the entire body of the program into a single task.
This change alone doubles the "CPU" time. There appears to be a 100% penalty
associated simply with running the original program from within a second task.

Anyone see what I'm doing wrong?
Any pitfalls to using tasking that I may have missed?

I suspect storage [de]allocation since that's under stress in this test, and
other benchmarks (e.g. Mandelbrot) don't see this penalty.
Should the task have its own separate storage pool, to avoid difficulties
synchronising with the main pool (even though the main program no longer uses
it?


----------------------------------------------------------------
-- BinaryTrees experimental version
--
-- Ada 95 (GNAT)
--
-- Contributed by Jim Rogers
-- Tasking experiment:  Brian Drummond
----------------------------------------------------------------
with Treenodes; use Treenodes;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;

procedure Binarytrees_tasktest is

   N : Natural := 1;

   task the_work is
      entry Start(Count :in Natural);
      entry Complete;
   end the_work;

   task body the_work is
      Min_Depth : constant Positive := 4;
      Stretch_Tree : TreeNode;
      Long_Lived_Tree : TreeNode;
      Short_Lived_Tree_1 : TreeNode;
      Short_Lived_Tree_2 : TreeNode;
      Max_Depth : Positive;
      Stretch_Depth : Positive;
      Check : Integer;
      Sum : Integer;
      Depth : Natural;
      Iterations : Positive;
   begin

      accept Start(Count :in Natural) do
         N := Count;
      end Start;

      Max_Depth := Positive'Max(Min_Depth + 2, N);
      Stretch_Depth := Max_Depth + 1;
      Stretch_Tree := Bottom_Up_Tree(0, Stretch_Depth);
      Item_Check(Stretch_Tree, Check);
      Put("stretch tree of depth ");
      Put(Item => Stretch_Depth, Width => 1);
      Put(Ht & " check: ");
      Put(Item => Check, Width => 1);
      New_Line;
   
      Long_Lived_Tree := Bottom_Up_Tree(0, Max_Depth);
   
      Depth := Min_Depth;
      while Depth <= Max_Depth loop
         Iterations := 2**(Max_Depth - Depth + Min_Depth);
         Check := 0;
         for I in 1..Iterations loop
            Short_Lived_Tree_1 := Bottom_Up_Tree(Item => I, Depth => Depth);
            Short_Lived_Tree_2 := Bottom_Up_Tree(Item =>-I, Depth => Depth);
            Item_Check(Short_Lived_Tree_1, Sum);
            Check := check + Sum;
            Item_Check(Short_Lived_Tree_2, Sum);
            Check := Check + Sum;
         end loop;
         Put(Item => Iterations * 2, Width => 0);
         Put(Ht & " trees of depth ");
         Put(Item => Depth, Width => 0);
         Put(Ht & " check: ");
         Put(Item => Check, Width => 0);
         New_Line;
         Depth := Depth + 2;
      end loop;
      Put("long lived tree of depth ");
      Put(Item => Max_Depth, Width => 0);
      Put(Ht & " check: ");
      Item_Check(Long_Lived_Tree, Check);
      Put(Item => Check, Width => 0);
      New_Line;
      accept Complete;
   end the_work;

begin
   if Argument_Count > 0 then
      N := Positive'Value(Argument(1));
   end if;
   the_work.start(N);
   the_work.complete;
end BinaryTrees_tasktest;

------------------------------------------------------



^ permalink raw reply	[relevance 4%]

* Re: Random number generation
  2010-12-30 10:43  5% Random number generation Mart van de Wege
  2010-12-30 11:34  0% ` Niklas Holsti
  2010-12-30 11:51  0% ` Brian Drummond
@ 2010-12-30 13:04  4% ` Dmitry A. Kazakov
  2 siblings, 0 replies; 200+ results
From: Dmitry A. Kazakov @ 2010-12-30 13:04 UTC (permalink / raw)


On Thu, 30 Dec 2010 11:43:40 +0100, Mart van de Wege wrote:

> Anyone care to at least point me to some documentation that explains
> what I'm doing wrong? 

Random generator is a stateful object, thus it cannot be local.

I suggest this is what you want:
--------------------------------------------------------------------------
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

with Ada.Numerics.Discrete_Random;

procedure Rolltest is
   package Uniform is new Ada.Numerics.Discrete_Random (Natural);
   use Uniform;

   function Roll
            (  Dice     : Generator;
               Number   : in Positive;
		   Size     : in Positive;
		   Modifier : in Integer := 0
            )  return Integer is 
      Result : Integer := 0;
   begin
      for I in 1..Number loop
	   Result := Result + Random (Dice) mod Size;
      end loop;
      Result := Result + Modifier + Number;
      return Result;
   end Roll;

   Dice : Generator;
begin
   Reset (Dice);
   for I in 1..10 loop
      Put (Roll (Dice => Dice, Number => 3, Size => 6));
   end loop;
end Rolltest;
-------------------------------------------------------------------------
I added Number to the accumulated result because you did so in your example
by choosing the range 2..Size.

BTW, a sum of n realizations of a uniformly distributed random number is
distributed uniformly with the factor n. So you need not to run a cycle
within Roll:

   function Roll
            (  Dice     : Generator;
               Number   : in Positive;
		   Size     : in Positive;
		   Modifier : in Integer := 0
            )  return Integer is 
   begin
      return Number * ((Random (Dice) mod Size) + 1) + Modifier;
   end Roll;
 
-- 
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de



^ permalink raw reply	[relevance 4%]

* Re: Random number generation
  2010-12-30 10:43  5% Random number generation Mart van de Wege
  2010-12-30 11:34  0% ` Niklas Holsti
@ 2010-12-30 11:51  0% ` Brian Drummond
  2010-12-30 13:04  4% ` Dmitry A. Kazakov
  2 siblings, 0 replies; 200+ results
From: Brian Drummond @ 2010-12-30 11:51 UTC (permalink / raw)


On Thu, 30 Dec 2010 11:43:40 +0100, Mart van de Wege <mvdwege@mail.com> wrote:

>Beginner's question: I'm trying to implement a function that rolls a
>number of dice and then adds a modifier. Somehow, it produces the same
>number every time. I can't see where I'm going wrong.
>
>Here's the proof of concept code:
>
>with Ada.Numerics.Discrete_Random,Ada.Integer_Text_IO;
>use Ada.Integer_Text_IO;
>
>procedure Rolltest is
>   function Roll ( Number : in Positive;
...
>      package Die is new Ada.Numerics.Discrete_Random( Die_Size );
...
>   begin
>      Die.Reset(G);
...
>   end Roll;
>begin
>   for I in 1..10 loop
>      Put(Roll( Number => 3, Size => 6 ));
>   end loop;
>end Rolltest;
>
>Anyone care to at least point me to some documentation that explains
>what I'm doing wrong? 

Check the documentation for  Ada.Numerics.Discrete_Random or at least its
specification ( .ads file) but I think you'll find you need to reset the Die
exactly once, rather than every call of the Roll function.

As I understand, you are resetting the seed each time, so you get the same
results!

The shortest way to resolve this is to make Die a global variable and reset it
at the start of the main program - in the context of a one-page beginner's
program it's a reasonable thing to do.

We're all taught "Global Variables are BAD" with good reason, so - once you have
resolved the immediate problem - it might be a good time to learn a bit about
packages, to hide the Die and expose only what you need to operate on it.

Essentially, within the package, Die can safely become a "global" variable, but
invisible and inaccessible outside the package, so that it appears more like a
static variable in a C function (holds the current random seed value between
calls).

- Brian



^ permalink raw reply	[relevance 0%]

* Re: Random number generation
  2010-12-30 10:43  5% Random number generation Mart van de Wege
@ 2010-12-30 11:34  0% ` Niklas Holsti
  2010-12-30 11:51  0% ` Brian Drummond
  2010-12-30 13:04  4% ` Dmitry A. Kazakov
  2 siblings, 0 replies; 200+ results
From: Niklas Holsti @ 2010-12-30 11:34 UTC (permalink / raw)


Mart van de Wege wrote:
> Beginner's question: I'm trying to implement a function that rolls a
> number of dice and then adds a modifier. Somehow, it produces the same
> number every time. I can't see where I'm going wrong.
> 
> Here's the proof of concept code:
> 
> with Ada.Numerics.Discrete_Random,Ada.Integer_Text_IO;
> use Ada.Integer_Text_IO;
> 
> procedure Rolltest is
>    function Roll ( Number : in Positive;
> 		   Size : in Positive;
> 		   Modifier : in Integer := 0 ) return Integer is 
>       subtype Die_Size is Positive range 2..Size;
>       package Die is new Ada.Numerics.Discrete_Random( Die_Size );
>       G : Die.Generator;
>       Result : Integer;
>       Temp : Integer;
>    begin
>       Die.Reset(G);

This Reset operation is specified (in RM A.5.2(34)) to set the state of 
the generator G to a "time-dependent" state.

If every call of Roll is returning the same results, perhaps the calls 
happen so rapidly that whatever discrete "time" source Reset uses is the 
same on each call, thus setting G to the same state on each call.

Ordinarily I would suggest to call Reset just once, and then let the 
state of the generator evolve without Resets over all calls of Roll, but 
this cannot be done here because G is a local variable in Roll, and it 
must be so since the generic actual parameter depends on the Size 
parameter of Roll.

Perhaps you should make another random Integer number generator IntGen, 
local to Rolltest but not to Roll, and use the generated Integer numbers 
to initialize Roll.G by a Reset call that has the random Integer as the 
second, state-determining "Initiator" parameter. The IntGen generator 
should be Reset in Rolltest, not in Roll, or left in its default initial 
state.

If you leave a random-number generator with its default initial state 
(no Reset call), you get the same random-number sequence on every execution.

If you use the single-parameter Reset (G) procedure, you get a sequence 
that is different for different executions, providing that the Resets 
are far enough apart in time to make a difference.

>       Result := 0;
>       for I in 1..Number loop
> 	 Temp := Die.Random(G);
> 	 Result := Result + Temp;
>       end loop;
>       Result := Result + Modifier;
>       return Result;
>    end Roll;
> begin
>    for I in 1..10 loop
>       Put(Roll( Number => 3, Size => 6 ));
>    end loop;
> end Rolltest;
> 
> Anyone care to at least point me to some documentation that explains
> what I'm doing wrong? 
> 
> Mart
> 


-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
       .      @       .



^ permalink raw reply	[relevance 0%]

* Random number generation
@ 2010-12-30 10:43  5% Mart van de Wege
  2010-12-30 11:34  0% ` Niklas Holsti
                   ` (2 more replies)
  0 siblings, 3 replies; 200+ results
From: Mart van de Wege @ 2010-12-30 10:43 UTC (permalink / raw)


Beginner's question: I'm trying to implement a function that rolls a
number of dice and then adds a modifier. Somehow, it produces the same
number every time. I can't see where I'm going wrong.

Here's the proof of concept code:

with Ada.Numerics.Discrete_Random,Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;

procedure Rolltest is
   function Roll ( Number : in Positive;
		   Size : in Positive;
		   Modifier : in Integer := 0 ) return Integer is 
      subtype Die_Size is Positive range 2..Size;
      package Die is new Ada.Numerics.Discrete_Random( Die_Size );
      G : Die.Generator;
      Result : Integer;
      Temp : Integer;
   begin
      Die.Reset(G);
      Result := 0;
      for I in 1..Number loop
	 Temp := Die.Random(G);
	 Result := Result + Temp;
      end loop;
      Result := Result + Modifier;
      return Result;
   end Roll;
begin
   for I in 1..10 loop
      Put(Roll( Number => 3, Size => 6 ));
   end loop;
end Rolltest;

Anyone care to at least point me to some documentation that explains
what I'm doing wrong? 

Mart

-- 
"We will need a longer wall when the revolution comes."
    --- AJS, quoting an uncertain source.



^ permalink raw reply	[relevance 5%]

* An Example for Ada.Execution_Time
@ 2010-12-27 18:26  5% anon
  0 siblings, 0 replies; 200+ results
From: anon @ 2010-12-27 18:26 UTC (permalink / raw)


You ask for an example.

Here is an example for packages (Tested using MaRTE):
  Ada.Execution_Time         -- Defines Time type and main operations as
                             -- well as the primary Clock for this type

  Ada.Execution_Time.Timers  -- Links to Timers 


Altering this example one could use a number of timers to be set 
using different times. Or testing a number of algorithms using 
the timer.

Also, I do have a Real_Time non-Task version that this example was 
based on.


-------------------------------
-- Work.adb -- Main program

with Ada.Integer_Text_IO ;
with Ada.Text_IO ;
with Work_Algorithm ;         -- Contains worker algorithm
with Work_Execution_Time ;    -- Contains execution Timing routines

procedure Work is

  use Ada.Integer_Text_IO ;
  use Ada.Text_IO ;
  use Work_Execution_Time ; 

  Task_0 : Work_Task ;

begin -- Work
  Initialize ( Work_Algorithm'Access ) ;
  Task_0.Start ( False ) ;

  -- Prints results of Test

  New_Line ;
  Put ( "Event occured " ) ;
  Put ( Item => Counter, Width => 3 ) ;
  Put_Line ( " Times." ) ;
  New_Line ;

end Work ;

-------------------------------
-- Work_Algorithm.ads

procedure Work_Algorithm ;

-------------------------------
-- Work_Algorithm.adb

with Ada.Integer_Text_IO ;
with Ada.Text_IO ;

procedure Work_Algorithm is
    use Ada.Integer_Text_IO ;
    use Ada.Text_IO ;
  begin
    for Index in 0 .. 15 loop
      Put ( "Paused =>" ) ;
      Put ( Index ) ;
      New_Line ;
      delay 1.0 ;
    end loop ;
  end Work_Algorithm ;


-------------------------------
-- Work.Execution_Time.ads

with Ada.Execution_Time ;
with Ada.Real_Time ;

package Work_Execution_Time is

  type Algorithm_Type is access procedure ;

  task type Work_Task is
    entry Start ( Active : in Boolean ) ;
  end Work_Task ;


  Counter    : Natural ;

  procedure Initialize ( A : in Algorithm_Type ) ;

private 

  Algorithm  : Algorithm_Type ;

  Start_Time : Ada.Execution_Time.CPU_Time ;
  At_Time    : Ada.Execution_Time.CPU_Time ;
  In_Time    : Ada.Real_Time.Time_Span ;

end Work_Execution_Time ;

-------------------------------
-- Work_Execution_Time ;
with Ada.Integer_Text_IO ;
with Ada.Text_IO ;
with Ada.Execution_Time ;
with Ada.Execution_Time.Timers ;
with Ada.Real_Time ;
with Ada.Task_Identification ;

package body Work_Execution_Time is


    use Ada.Execution_Time ;
    use Ada.Real_Time ;
    use Timers ;

    package D_IO is new Ada.Text_IO.Fixed_IO ( Duration ) ;
    package S_IO is new Ada.Text_IO.Integer_IO
                                      ( Ada.Real_Time.Seconds_Count ) ;

  protected Handlers is
    -- Handler: Single Event
      procedure Handler_1 ( TM : in out Timer ) ;

    -- Handler: Multple Event
      procedure Handler_2 ( TM : in out Timer ) ;
  end Handlers ;



  task body Work_Task is

      use Ada.Task_Identification ;

    ID         : aliased Task_Id := Current_Task ;
    TM         : Timers.Timer ( ID'Access ) ;

    Cancelled  : Boolean := False ;

  begin
    Counter := 0 ;
    loop
      select
        Accept Start ( Active : in Boolean ) do
          if Active then
            Start_Time := Ada.Execution_Time.Clock ;
            At_Time := Start_Time + Milliseconds ( 5 ) ;
            Set_Handler ( TM, AT_Time, Handlers.Handler_2'Access ) ;
          else
            Start_Time := Ada.Execution_Time.Clock ;
            In_Time := Milliseconds ( 10 ) ;
            Set_Handler ( TM, In_Time, Handlers.Handler_2'Access ) ;
          end if ;

          Algorithm.all ;  -- Execute Test algorithm

          Timers.Cancel_Handler ( TM, Cancelled ) ;
        end Start ;
      or
        terminate ;
      end select ;
    end loop ;
  end Work_Task ;


  --
  -- Timer Event Routines
  --
  protected body Handlers is 

    -- Handler: Single Event

    procedure Handler_1 ( TM : in out Timer ) is

        Value     : Time_Span ;
        Cancelled : Boolean ;

      begin
        Value := Time_Remaining ( TM ) ;
        Ada.Text_IO.Put ( "Timing Event Occured at " ) ;
        D_IO.Put ( To_Duration ( Value ) ) ;
        Ada.Text_IO.New_Line ;
        Counter := Counter + 1 ;
        Cancel_Handler ( TM, Cancelled ) ;
      end Handler_1 ;

    -- Handler: Multple Event

    procedure Handler_2 ( TM : in out Timer ) is

        Value   : Time_Span ;

      begin
        Value := Time_Remaining ( TM ) ;
        Ada.Text_IO.Put ( "Timing Event Occured at " ) ;
        D_IO.Put ( To_Duration ( Value ) ) ;
        Ada.Text_IO.New_Line ;
        Counter := Counter + 1 ;

        Start_Time := Ada.Execution_Time.Clock ;
        In_Time := Ada.Real_Time.Milliseconds ( 10 ) ;
        Set_Handler ( TM, In_Time, Handlers.Handler_2'Access ) ;
      end Handler_2 ;

  end Handlers ;


  -- Initialize: Set Algorithm and Counter

  procedure Initialize ( A : in Algorithm_Type ) is
    begin
      Algorithm := A ;
      Counter := 0 ;
    end Initialize ;

end Work_Execution_Time ;




^ permalink raw reply	[relevance 5%]

* Problems with network printer
@ 2010-12-23 15:37  5% tchaco
  0 siblings, 0 replies; 200+ results
From: tchaco @ 2010-12-23 15:37 UTC (permalink / raw)


I am having problems with network printer using ADA.
I would like to know how to name correctly the File adress instead of
the standard "LPT1".
I'm using GNAT Pro 5.04a1.

A example  is shown bellow.

with Ada.Text_Io, Ada.Integer_Text_Io;
use Ada.Text_Io, Ada.Integer_Text_Io;

procedure Printout is

   Turkey : File_Type;

begin

   Create(Turkey, Out_File, "LPT1");
   Put(Turkey, "This is a test of turkey");
   New_Line(Turkey);
   Put(Turkey, "and it should work well.");
   New_Line(Turkey, 2);
   Put("Half of the turkey test.");
   New_Line;

   Set_Output(Turkey);
   Put("This is another test of turkey");
   New_Line;
   Put("and it should work well.");
   New_Line(2);
   Put(Standard_Output, "Half of the turkey test.");
   New_Line(Standard_Output);
   Set_Output(Standard_Output);

   Put("Back to the standard default output.");

   Close(Turkey);

end Printout;



Any suggestions ?

Thank you

Giacomo



^ permalink raw reply	[relevance 5%]

* Re: Callback in Ada
  @ 2010-11-27 10:26  5% ` Alex Mentis
  0 siblings, 0 replies; 200+ results
From: Alex Mentis @ 2010-11-27 10:26 UTC (permalink / raw)


Georg Maubach wrote:

> Hi All,
> 
> today I learnt what a callback function is and also how it is used in 
> Python. I have tested the following code which runs in Python:
> 
> def apply_to (function, valueList):
>    resultList = []
> 
>    if __debug__: print "Calling function ", function
>    
>    for value in valueList:
>       if __debug__: print "value: ", value
>       r = function (value)
>       if __debug__: print "result: ", r
>       resultList.append(r)
> 
>    return resultList
> 
> def dublicate (value):
>    return (value * 2)
> 
> def power (value):
>    return (value * value)
> 
> valueList = [1, 2, 3, 4, 5]
> 
> double_values = apply_to(dublicate, valueList)
> power_values = apply_to(power, valueList)
> 
> print "Values doubled: ", double_values
> print "Values powered: ", power_values
> 
> Reference: http://en.wikipedia.org/wiki/Callback_(computer_science)
> 
> If put into a file called "callback-test-in-python.py" and called
> python -O callback-test-in-python.py it will deliver the output
> 
> Values doubled: 2, 4, 6, 8, 10
> Values powered: 1, 4, 9, 16, 25
> 
> How would I do that in Ada?
> 
> Regards
> 
> George

Basically the same idea as Dimitry, except I use functions so the code
works more similarly to your Python:

with Ada.Text_IO, Ada.Integer_Text_IO;
use  Ada.Text_IO, Ada.Integer_Text_IO;

procedure Callback is
   
   type Int_Array is array (1..5) of Integer;
   
   function Apply_To 
     (Func       : not null access function (Value : Integer) return
Integer;
      Value_List : Int_Array) return Int_Array is            
      
      Result : Int_Array;
      
   begin -- Apply_To
      for Value in Value_List'Range loop
         Result (Value) := Func (Value_List(Value));
      end loop;
      return Result;
   end Apply_To;       
   
   function  Dublicate (Value : Integer) return Integer is
   begin -- Dublicate
      return Value * 2;
   end Dublicate;
   
   Initial : Int_Array := (1, 2, 3, 4, 5);
   Result : Int_Array;
   
begin
   
   Result := Apply_To (Dublicate'Access, Initial);
   
   Put("Values doubled: ");
   for Value in Result'Range loop
      Put (Result (Value), 0);
      if Value /= Result'Last then
         Put (", ");
      end if;
   end loop;
   
end Callback;



^ permalink raw reply	[relevance 5%]

* Re: Beginners question: Compound types, how-to?
  2010-11-01  3:55  0% ` Jeffrey Carter
@ 2010-11-01  7:12  0%   ` Mart van de Wege
  0 siblings, 0 replies; 200+ results
From: Mart van de Wege @ 2010-11-01  7:12 UTC (permalink / raw)


Jeffrey Carter <spam.jrcarter.not@spam.not.acm.org> writes:

> On 10/31/2010 03:00 PM, Mart van de Wege wrote:
>>
>> games-rpg-dnd.ads:
>> --with Games.RPG;
>> -- Ignore parent package for now, we don't need the
>> -- utility functions yet.
>
> Children always have visibility into the specs of their ancestors, so
> you never need to "with" said ancestors.
>
Cool. I missed this tidbit in the texts I read. I suppose this *is*
spelled out in the Reference Manual?

>> with Games.RPG.DnD, Ada.Text_IO, Ada.Integer_Text_IO;
>> use Games.RPG.DnD, Ada.Text_IO, Ada.Integer_Text_IO;
>>
>> procedure Test_Game is
>>     C : Character;
>
> You have 2 things named Character at this point: Standard.Character,
> an enumeration type, and Standard.Games.RPG.DND.Character, a record
> type. 

Thanks to Jeffrey and the others. Yes, this was an elementary mistake,
and I kept overlooking it because I also have C experience, so I kept
reading Character as a perfectly fine identifier and dismissing Char
because I thought it was a reserved word.

I should have realised sooner that Ada uses full words, not
abbreviations, whenever possible.

I recompiled with Char as the type name; it looks ugly, but I think I
know a way around that, but that involves inheritance, and I am not
touching that just yet. 

My test code works fine now. I am relieved at least to know that my
logic was sound, even if the code wasn't particularly.

Mart
-- 
"We will need a longer wall when the revolution comes."
    --- AJS, quoting an uncertain source.



^ permalink raw reply	[relevance 0%]

* Re: Beginners question: Compound types, how-to?
  2010-10-31 22:00  5% Beginners question: Compound types, how-to? Mart van de Wege
@ 2010-11-01  3:55  0% ` Jeffrey Carter
  2010-11-01  7:12  0%   ` Mart van de Wege
  0 siblings, 1 reply; 200+ results
From: Jeffrey Carter @ 2010-11-01  3:55 UTC (permalink / raw)


On 10/31/2010 03:00 PM, Mart van de Wege wrote:
>
> games-rpg-dnd.ads:
> --with Games.RPG;
> -- Ignore parent package for now, we don't need the
> -- utility functions yet.

Children always have visibility into the specs of their ancestors, so you never 
need to "with" said ancestors.

> with Games.RPG.DnD, Ada.Text_IO, Ada.Integer_Text_IO;
> use Games.RPG.DnD, Ada.Text_IO, Ada.Integer_Text_IO;
>
> procedure Test_Game is
>     C : Character;

You have 2 things named Character at this point: Standard.Character, an 
enumeration type, and Standard.Games.RPG.DND.Character, a record type. 
Standard.Character is directly visible, and the other is "use visible", visible 
due to a use clause. The rule is that something that is use visible cannot hide 
something that is directly visible. Since both can't be referenced by the simple 
name Character, this must refer to the one that is directly visible, 
Standard.Character.

Things are different for subprograms, which can be overloaded; then both may be 
visible and referred to by the simple name.

But it's usually a good idea for a beginner to avoid use clauses.

-- 
Jeff Carter
"Why, the Mayflower was full of Fireflies, and a few
horseflies, too. The Fireflies were on the upper deck,
and the horseflies were on the Fireflies."
Duck Soup
95



^ permalink raw reply	[relevance 0%]

* Beginners question: Compound types, how-to?
@ 2010-10-31 22:00  5% Mart van de Wege
  2010-11-01  3:55  0% ` Jeffrey Carter
  0 siblings, 1 reply; 200+ results
From: Mart van de Wege @ 2010-10-31 22:00 UTC (permalink / raw)


Hi,

I've been playing around with Ada for a bit, and like it. To teach it to
myself, I am rewriting some Perl code I wrote for hobby purposes, yet I
can't seem to get my head around how to use compound types.

I have the following code (yes, I'm an RPG geek, sorry):

games-rpg-dnd.ads:
--with Games.RPG;
-- Ignore parent package for now, we don't need the
-- utility functions yet.
package Games.RPG.DnD is
   type Ability_Type is (Str, Dex, Con, Int, Wis, Cha);
   type Ability is
      record
	 Score : Natural;
	 Modifier : Integer;
      end record;
   type Ability_Array is array (Ability_Type) of Ability;
   type Character is 
      record
	 Abilities : Ability_Array;
      end record;
end Games.RPG.DnD;

test-game.adb:
with Games.RPG.DnD, Ada.Text_IO, Ada.Integer_Text_IO;
use Games.RPG.DnD, Ada.Text_IO, Ada.Integer_Text_IO;

procedure Test_Game is
   C : Character;
begin
   C.Abilities(Str) := (Score => 10, Modifier => -1);
   Put (C.Abilities(Str).Score);
   put (C.Abilities(Str).Modifier);
end Test_Game;

When I do it like this:

with Games.RPG.DnD, Ada.Text_IO, Ada.Integer_Text_IO;
use Games.RPG.DnD, Ada.Text_IO, Ada.Integer_Text_IO;

procedure Test_Game is
   A : Ability_Array;
begin
   A(Str) := (Score => 10, Modifier => -1);
   Put (A(Str).Score);
   put (A(Str).Modifier);
end Test_Game;

It works, when I use the former code, it bombs with 'Invalid prefix in
selected component "C"';

What am I doing wrong? I am misunderstanding something, but what? C
should be a record containing an Ability_Array as its first field, so I
should be able to index into it using an Ability_Type subscript. How do
I do this?

Mart
-- 
"We will need a longer wall when the revolution comes."
    --- AJS, quoting an uncertain source.



^ permalink raw reply	[relevance 5%]

* loop problem with exit condition
@ 2010-09-26  8:14  4% Ada novice
  0 siblings, 0 replies; 200+ results
From: Ada novice @ 2010-09-26  8:14 UTC (permalink / raw)


Hi,
    I'm putting a simple code below with two loops. The Outer loop
ranges from -44.88 to 67.32 and should be subdivided equally in 300
points. The Inner loop ranges from 0.001 to 0.35 and should also be
subdivided in 300 points. I would like the limits of the range to be
included i.e. Outer loop has as first value -44.88 and last value as
67.32 . Inner loop has as first value 0.001 and last value as 0.35 .
Here's my code:

with Ada.Text_IO;
with Ada.Long_Float_Text_IO;
with Ada.Integer_Text_IO;



procedure Try is

   Count : Integer;
   Outer : Long_Float;
   Outer_Start : constant := -44.88;
   Outer_Limit : constant := 67.32;
   Outer_Step : constant := (Outer_Limit - Outer_Start)/299.0;

   Inner : Long_Float;
   Inner_Start : constant := 0.001;
   Inner_Limit : constant := 0.35;
   Inner_Step : constant := (Inner_Limit - Inner_Start)/99.0;


begin

   Count := 0;
   Outer := Outer_Start;


   loop
        Inner := Inner_Start;

        loop
          Count := Count + 1;

          exit when Inner > Inner_Limit - Inner_Step;

          Inner := Inner + Inner_Step;

   end loop;

      exit when Outer > Outer_Limit - Outer_Step;

      Outer := Outer + Outer_Step;


end loop;


      Ada.Text_IO.New_Line(2);
      Ada.Text_IO.Put("Inner after loop is (should be 0.35) ");
      Ada.Long_Float_Text_IO.Put (Item => Inner, Fore => 3, Aft  => 3,
Exp  => 0);
      Ada.Text_IO.New_Line(2);
      Ada.Text_IO.Put("Count after loop is ");
      Ada.Integer_Text_IO.Put (Item => Count);



end Try;


I am not able to get this working fine. The total time that both loops
should be entered must be 300 * 100 = 30k. I'm getting only Count as
29,700 and inner to be 0.346  (I understand that this is cause by my
exit condition).

How to create loops that follow my specifications?


Thanks a lot..







^ permalink raw reply	[relevance 4%]

* Re: Inefficient algorithms
  @ 2010-09-15  1:11  5% ` BrianG
  0 siblings, 0 replies; 200+ results
From: BrianG @ 2010-09-15  1:11 UTC (permalink / raw)


Rick wrote:
> I am working on a class in algorithmic efficiency and, to make a
> point, need an algorithm that runs O(2^n) - a factoring algorithm
> perhaps.  All I can find is 'C' code I can't decipher.  Can someone
> please help with an Ada example.
> 
> Thanks
Um, after reading all the responses to date, I don't uderstand what's so 
hard about coming up with an _IN_efficient example.  I'd think any first 
year programming class ought to provide at least one good example.

How about:

------------------------------------------------------------------------------- 

-- Bad_Sort.Ada - Example of O(n^2) code
------------------------------------------------------------------------------- 

    with Ada.Text_IO, Ada.Integer_Text_IO;
    use  Ada.Text_IO, Ada.Integer_Text_IO;
procedure Bad_Sort is
    type My_Array is array (Natural range <>) of Integer;
    function Sort (This : My_Array) return My_Array is
       Input  : My_Array := This;
       Result : My_Array (This'first..This'last);
       Min, Index : Integer;
    begin
       for I in Result'range loop
          Min := Integer'last;
          Index := Input'first-1;
          for J in Input'range loop
             if Input(J) < Min then
                Min := Input(J);
                Index := J;
             end if;
          end loop;
          Result(I) := Min;
          if Index >= Input'first then
             Input(Index) := Integer'last;
          end if;
       end loop;
       return Result;
    end Sort;
    --
    Test : My_Array := (1, 3, 2, 5, 7, 4, 9, 8, 6, 0);
    Answ : My_Array := Sort(Test);
begin
    Put("Input: ");
    for I in Test'range loop
       Put(Test(I));
    end loop;
    New_Line;
    Put("Output:");
    for I in Answ'range loop
       Put(Answ(I));
    end loop;
    New_Line;
end Bad_Sort;

(of course, this is an O(n^2) implementation; maybe that's not what you 
meant :-)



^ permalink raw reply	[relevance 5%]

* Re: Min/Max attribute makes promises it can't keep
  @ 2010-04-28 10:36  5%     ` Alex Mentis
  0 siblings, 0 replies; 200+ results
From: Alex Mentis @ 2010-04-28 10:36 UTC (permalink / raw)


On Apr 27, 5:16 pm, Robert A Duff <bobd...@shell01.TheWorld.com>
wrote:
> Martin <martin.do...@btopenworld.com> writes:
> >    Put (Positive (Positive'Min(Nat, Pos)));
>
> That works, but I think a qualified expression is better:
>
>    Put (Positive'(Positive'Min(Nat, Pos)));
>
> By the way, there are lots of attributes that work
> like this (use the base subtype).  It's not just Min
> and Max.
>
> - Bob

I think you all missed my point: allowing the programmer to specify a
constraint in situations where the constraint will not be enforced
could cause confusion/error for someone who doesn't have the entire
ARM memorized....

Yes, I know there are ways to force Ada to do the check, like explicit
type conversion and qualified expressions.  That's pretty ugly,
though.  If I already have to put the type in front of the attribute,
why should I have to put the type in front of that again?  As long as
we're posting work-arounds, though, I suppose I would use the
following:

with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;

procedure Main is

   function Min(Value_1, Value_2 : Integer) return Integer renames
Integer'Min;

   Nat : constant Natural := 0;
   Pos : Positive;

begin

   Get (Pos);
   Put (Positive'(Min(Nat, Pos))); -- return a Positive result from
renamed Min else raise a Constraint_Error

end Main;



^ permalink raw reply	[relevance 5%]

* Re: Min/Max attribute makes promises it can't keep
  2010-04-27 19:34  4% Min/Max attribute makes promises it can't keep Alex Mentis
@ 2010-04-27 20:20  0% ` Martin
    0 siblings, 1 reply; 200+ results
From: Martin @ 2010-04-27 20:20 UTC (permalink / raw)


On Apr 27, 8:34 pm, Alex Mentis <asmen...@gmail.com> wrote:
> I'm disappointed with some allowed syntax that seems a little error-
> prone.  Consider the following code:
>
> with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
>
> procedure Main is
>
>    Nat : constant Natural := 0;
>    Pos : Positive;
>
> begin
>
>    Get (Pos);
>    Put (Positive'Min(Nat, Pos)); -- Ada does not require the Min
> attribute to enforce a Positive result
>
> end Main;
>
> This program happily outputs that the minimum of (0 and whatever
> positive value you enter) is 0.  Now, I concede that the program is
> working exactly as the ARM specifies.  The Min (and Max) attribute
> functions accept and return types of S'Base, in this case
> Positive'Base.  But doesn't it seem like a bit of a tease to allow a
> programmer to specify S'Min if the compiler is allowed to ignore the
> type of S in the function's parameter list and the program does not
> raise a Constraint_Error at run-time if it returns a value outside the
> range of type S?
>
> If it's too hard to enforce strictly then maybe the functions should
> be named Unchecked_Min/Unchecked_Max.  Or maybe the programmer should
> be constrained to using the attributes with only a base type.  Or, at
> the very least, can't the compiler generate a warning about this?  I
> turned on all warnings in GPS and got nothing.
>
> Things that make you go hmmm...
>
> Alex

If you want the check, this should do:

begin
   Get (Pos);
   Put (Positive (Positive'Min(Nat, Pos)));
end ...

-- Martin



^ permalink raw reply	[relevance 0%]

* Min/Max attribute makes promises it can't keep
@ 2010-04-27 19:34  4% Alex Mentis
  2010-04-27 20:20  0% ` Martin
  0 siblings, 1 reply; 200+ results
From: Alex Mentis @ 2010-04-27 19:34 UTC (permalink / raw)


I'm disappointed with some allowed syntax that seems a little error-
prone.  Consider the following code:

with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;

procedure Main is

   Nat : constant Natural := 0;
   Pos : Positive;

begin

   Get (Pos);
   Put (Positive'Min(Nat, Pos)); -- Ada does not require the Min
attribute to enforce a Positive result

end Main;

This program happily outputs that the minimum of (0 and whatever
positive value you enter) is 0.  Now, I concede that the program is
working exactly as the ARM specifies.  The Min (and Max) attribute
functions accept and return types of S'Base, in this case
Positive'Base.  But doesn't it seem like a bit of a tease to allow a
programmer to specify S'Min if the compiler is allowed to ignore the
type of S in the function's parameter list and the program does not
raise a Constraint_Error at run-time if it returns a value outside the
range of type S?

If it's too hard to enforce strictly then maybe the functions should
be named Unchecked_Min/Unchecked_Max.  Or maybe the programmer should
be constrained to using the attributes with only a base type.  Or, at
the very least, can't the compiler generate a warning about this?  I
turned on all warnings in GPS and got nothing.

Things that make you go hmmm...

Alex



^ permalink raw reply	[relevance 4%]

* Gnatbench 2.3.1 doing funny thing - any ideas?
@ 2009-08-05 10:40  2% John McCabe
  0 siblings, 0 replies; 200+ results
From: John McCabe @ 2009-08-05 10:40 UTC (permalink / raw)


I'm playing around with Eclipse Ganymede and Gnatbench (again).

I have a strange thing happening in the editor and haven't the
faintest idea where to look to see why this is happening so I hope
someone can point me in the right direction.

Basically I have a little program, just playing with it as a bit of a
reminder as I don't use Ada in anger these days...

1 ) with Ada.Text_Io;
2 ) with Ada.Integer_Text_Io;
3 ) with Ada.Exceptions;
4 )
5 ) procedure Mainproc is
6 )
7 )    protected type Mutex_Type is
8 )       entry Wait;
9 )       procedure Release;
10)    private
11)       Open : Boolean := True;
12)    end Mutex_Type;
13)
14)    protected body Mutex_Type is
15)       entry Wait when Open is
16)       begin
17)          Open := False;
18)       end Wait;
19)
20)       procedure Release is
21)       begin
22)          Open := True;
23)       end Release;
24)    end Mutex_Type;
25)
26)    Mutex_Po : Mutex_Type;
27)
28)    task type Synctask_Po (Id : Integer) is
29)       entry Startup;
30)    end Synctask_Po;
31)
32)    task body Synctask_Po is
33)       Usual_Delay : constant Duration := 1.0 + Duration (Id) /
10.0;
34)    begin
35)       accept Startup;
36)       while True
37)       loop
38)          Ada.Text_Io.Put_Line ("Task" & Integer'Image(Id) & ":
Waiting for Entry");
39)          Mutex_Po.Wait;
40)
41)          Ada.Text_Io.Put_Line ("Task" & Integer'Image(Id) & ": in
Critical Section");
42)          delay Usual_Delay;
43)
44)          Ada.Text_Io.Put_Line ("Task" & Integer'Image(Id) & ":
Releasing");
45)          Mutex_Po.Release;
46)          delay Usual_Delay;
47)       end loop;
48)    exception
49)       when X : others =>
50)          Ada.Text_Io.Put ("Exception occurred in synctask_po" &
51)                           Integer'Image(Id) &
52)                           ": " &
53)                           Ada.Exceptions.Exception_Name
(Ada.Exceptions.Exception_Identity (X)) &
54)                           " : " &
55)                           Ada.Exceptions.Exception_Message (X));
56)    end Synctask_Po;
57)
58)    type Synctask_Po_Access is access all Synctask_Po;
59)    Synctask_Po_Arr : array (1 .. 3) of Synctask_Po_Access;
60)
61) begin
62)    for I in 1 .. 3 loop
63)       Synctask_Po_Arr (I) := new Synctask_Po (I);
64)       Synctask_Po_Arr (I).Startup;
65)    end loop;
66) 
67) end Mainproc;

Now, on most lines, if I go to the start of the line and press the
enter key, it just gives me a blank line and moves the line I'm on
down one, putting the cursor at the start of the text. However, on
lines 38, 41 and 44 if I do that, it does the same sort of thing, but
prepends an extra "A" on to the line, so I get AAda.Text_Io...

In the Ada preferences, "Editor" section, I've got:

Save altered files before completion
Remove trailing spaces when saving
NOT Use smart space key
Minimum word lenght for expansion consideration = 3
Use smart tab key
Highlight matching brackets
Matching brackets highlight color [kind of grey]
NOT Insert header text into new Ada aource files
File containing.... both blank.

In the "Coding Style" I've got...
extended
3
2
1
3
0
automatic
lower_case
Mixed_Case
Format operators/delimiters
NOT use tabulations
NOT align colons
NOT align associations
NOT align declaration
Indent comments
NOT align comments

Any ideas anyone?

Thanks
John



^ permalink raw reply	[relevance 2%]

* Re: Can a child access private types of its parent?
  2009-07-21 11:42  4% Can a child access private types of its parent? vlc
  2009-07-21 12:05  5% ` Dmitry A. Kazakov
@ 2009-07-21 12:07  5% ` Martin
  1 sibling, 0 replies; 200+ results
From: Martin @ 2009-07-21 12:07 UTC (permalink / raw)


On Jul 21, 12:42 pm, vlc <just.another.spam.acco...@googlemail.com>
wrote:
> Hi *,
>
> in the following code extract, I try to access a private variable I
> (line 09) in the Parent's type P from Child (in function Get, line
> 23):
>
> 01  with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
> 02
> 03  procedure Main is
> 04
> 05  package Parent is
> 06        type P is tagged private;
> 07     private
> 08        type P is tagged record
> 09           I : integer := 5;
> 10        end record;
> 11     end Parent;
> 12
> 13     package Child is
> 14        type C is new Parent.P with private;
> 15        function Get (This : C) return integer;
> 16     private
> 17        type C is new Parent.P with null record;
> 18     end Child;
> 19
> 20     package body Child is
> 21        function Get (This : C) return integer is
> 22        begin
> 23           return This.I;
> 24        end Get;
> 25     end Child;
> 26
> 27     Var : Child.C;
> 28
> 29  begin
> 30
> 31     Put (Var.Get);
> 32
> 33  end Main;
>
> But the compiler gives me a
> main.adb:23:21: no selector "I" for type "C" defined at line 17
>
> The code compiles if I make the type P public, i.e. if I comment the
> lines 06 and 07, the code compiles as the variable I gets inherited to
> Child. But then everybody can not only read but also write Var.I, e.g.
>
> 29  begin
> 30
> 31     Var.I := 2;
> 32     Put (Var.Get);
> 33
> 34  end Main;
>
> Is there a way to inherit private types from a Parent to its child?
>
> Thank a lot in advance for any help!

You need to make the Parent - Child packages (at library level).

e.g.
-- File: parent.ads
package Parent is
   -- As you have
end Parent;

-- File: parent-child.ads
package Parent.Child is
   -- Rest as you have, or you can miss the "Parent." bit, e.g.
   -- type C is new P with private;
   ...
end Parent.Child;

-- File: parent-child.adb
package body Parent.Child is
   -- Rest as you have
end Parent.Child;

-- File: main.adb
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Parent.Child;

procedure Main is
   Var : Parent.Child.C;
begin
   Put (Var.Get);
end Main;

Cheers
-- Martin



^ permalink raw reply	[relevance 5%]

* Re: Can a child access private types of its parent?
  2009-07-21 11:42  4% Can a child access private types of its parent? vlc
@ 2009-07-21 12:05  5% ` Dmitry A. Kazakov
  2009-07-21 12:07  5% ` Martin
  1 sibling, 0 replies; 200+ results
From: Dmitry A. Kazakov @ 2009-07-21 12:05 UTC (permalink / raw)


On Tue, 21 Jul 2009 04:42:36 -0700 (PDT), vlc wrote:

> in the following code extract, I try to access a private variable I
> (line 09) in the Parent's type P from Child (in function Get, line
> 23):
> 
> 01  with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
> 02
> 03  procedure Main is
> 04
> 05  package Parent is
> 06        type P is tagged private;
> 07     private
> 08        type P is tagged record
> 09           I : integer := 5;
> 10        end record;
> 11     end Parent;
> 12
> 13     package Child is
> 14        type C is new Parent.P with private;
> 15        function Get (This : C) return integer;
> 16     private
> 17        type C is new Parent.P with null record;
> 18     end Child;
> 19
> 20     package body Child is
> 21        function Get (This : C) return integer is
> 22        begin
> 23           return This.I;
> 24        end Get;
> 25     end Child;
> 26
> 27     Var : Child.C;

> Is there a way to inherit private types from a Parent to its child?

Child is not a child of Parent. Move Parent out of Main to the library
level and make Child also a library package named Parent.Child. I.e.

package Parent is
   type P is tagged private;
private
   type P is tagged record
      I : integer := 5;
   end record;
end Parent;

package Parent.Child is
   type C is new Parent.P with private;
   function Get (This : C) return integer;
private
   type C is new Parent.P with null record;
end Parent.Child;

package body Parent.Child is
   function Get (This : C) return integer is
   begin
      return This.I;
   end Get;
end Parent.Child;

with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Parent.Child;

procedure Main is
   Var : Parent.Child.C;
begin
   Put (Var.Get);
end Main;

-- 
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de



^ permalink raw reply	[relevance 5%]

* Can a child access private types of its parent?
@ 2009-07-21 11:42  4% vlc
  2009-07-21 12:05  5% ` Dmitry A. Kazakov
  2009-07-21 12:07  5% ` Martin
  0 siblings, 2 replies; 200+ results
From: vlc @ 2009-07-21 11:42 UTC (permalink / raw)


Hi *,

in the following code extract, I try to access a private variable I
(line 09) in the Parent's type P from Child (in function Get, line
23):

01  with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
02
03  procedure Main is
04
05  package Parent is
06        type P is tagged private;
07     private
08        type P is tagged record
09           I : integer := 5;
10        end record;
11     end Parent;
12
13     package Child is
14        type C is new Parent.P with private;
15        function Get (This : C) return integer;
16     private
17        type C is new Parent.P with null record;
18     end Child;
19
20     package body Child is
21        function Get (This : C) return integer is
22        begin
23           return This.I;
24        end Get;
25     end Child;
26
27     Var : Child.C;
28
29  begin
30
31     Put (Var.Get);
32
33  end Main;

But the compiler gives me a
main.adb:23:21: no selector "I" for type "C" defined at line 17

The code compiles if I make the type P public, i.e. if I comment the
lines 06 and 07, the code compiles as the variable I gets inherited to
Child. But then everybody can not only read but also write Var.I, e.g.

29  begin
30
31     Var.I := 2;
32     Put (Var.Get);
33
34  end Main;

Is there a way to inherit private types from a Parent to its child?

Thank a lot in advance for any help!



^ permalink raw reply	[relevance 4%]

* Re: float confusion
  2009-07-15  0:03  0%   ` Rob Solomon
@ 2009-07-15  0:18  0%     ` Adam Beneschan
  0 siblings, 0 replies; 200+ results
From: Adam Beneschan @ 2009-07-15  0:18 UTC (permalink / raw)


On Jul 14, 5:03 pm, Rob Solomon <use...@drrob1-noreply.com> wrote:
> On Tue, 14 Jul 2009 16:50:20 -0700 (PDT), Adam Beneschan
>
>
>
>
>
> <a...@irvine.com> wrote:
> >> with Ada.Text_IO;
> >> with Ada.Integer_Text_IO;
> >> with Ada.Float_Text_IO;
> >> use Ada.Text_IO;
> >> use Ada.Integer_Text_IO;
> >> use Ada.Float_Text_IO;
>
> >>    procedure SimpleCompute is
>
> >>    X : Integer := 1;
> >>    c : Integer := 0;  -- counter
> >>    N : Natural := 1;
> >>    P : Positive := 1;
> >>    F : Float := 1.0;
>
> >>    begin
> >>    put_line("X C N P F");
> >>    loop
> >>     put(X);
> >>     put(c,3);
> >>     put(n);
> >>     put(' ');
> >>     put(p);
> >>     put(' ');
> >>     put(f,15,0,0);
> >>     New_Line;
> >>     X := X * 2;
> >>     n := n * 2;
> >>     p := p + p;
> >>     f := f * 2.0;
> >>     c := c +1;
> >>     exit when c > 40;
> >>    end loop;
> >>    exception
> >>       when constraint_error =>
> >>          n := 1;
> >>    end simplecompute;
>
> >> And interestingly, I get overflow errors from the *2 statement but not
> >> from self+self.
>
> >How can you tell?  Your above example gives you no way to tell what
> >line you get an overflow on.  And the way it's written, if you got an
> >overflow on X := X*2, the exception would take you out of the loop and
> >you'd never get to the p := p+p statement for the same value (since it
> >looks like X=n=p will always be true at the beginning of the loop).
>
> Ok.  I got this example from the online tutorial and I kept modifying
> it to try something new.  Before I experimented w/  exception
> handling, I was getting constraint_error exceptions.  
>
> But Jeff Carter above explained that was I was seeing was really range
> checking effects and not overflow effects.  That helped me understand
> what was going on

Well, maybe.  Jeff said that Natural and Positive have range
constraints that Integer does not; however, those constraints prevent
objects from having negative values (or zero, for Positive), and since
your program is working only with positive numbers, that shouldn't
have had an effect.  However, if you don't have overflow checking on (-
gnato), then what happens is that when you get to the largest possible
power of 2, which is 2**30 for a 32-bit integer, and then double it,
the result will be seen as negative (-2**31), which (without overflow
checking) will cause a Constraint_Error for a Natural or Positive but
no exception at all for an Integer.  So in your example, this would
mean "n:=n*2" and "p:=p+p" would have raised exceptions, but "X:=X*2"
would not.  So I'm still not clear on why you'd think this is a
difference between multiplication and addition, unless you were
experimenting with different code earlier.

                                   -- Adam




^ permalink raw reply	[relevance 0%]

* Re: float confusion
  2009-07-14 23:50  0% ` Adam Beneschan
@ 2009-07-15  0:03  0%   ` Rob Solomon
  2009-07-15  0:18  0%     ` Adam Beneschan
  0 siblings, 1 reply; 200+ results
From: Rob Solomon @ 2009-07-15  0:03 UTC (permalink / raw)


On Tue, 14 Jul 2009 16:50:20 -0700 (PDT), Adam Beneschan
<adam@irvine.com> wrote:

>> with Ada.Text_IO;
>> with Ada.Integer_Text_IO;
>> with Ada.Float_Text_IO;
>> use Ada.Text_IO;
>> use Ada.Integer_Text_IO;
>> use Ada.Float_Text_IO;
>>
>> � �procedure SimpleCompute is
>>
>> � �X : Integer := 1;
>> � �c : Integer := 0; �-- counter
>> � �N : Natural := 1;
>> � �P : Positive := 1;
>> � �F : Float := 1.0;
>>
>> � �begin
>> � �put_line("X C N P F");
>> � �loop
>> � � put(X);
>> � � put(c,3);
>> � � put(n);
>> � � put(' ');
>> � � put(p);
>> � � put(' ');
>> � � put(f,15,0,0);
>> � � New_Line;
>> � � X := X * 2;
>> � � n := n * 2;
>> � � p := p + p;
>> � � f := f * 2.0;
>> � � c := c +1;
>> � � exit when c > 40;
>> � �end loop;
>> � �exception
>> � � � when constraint_error =>
>> � � � � �n := 1;
>> � �end simplecompute;
>>
>> And interestingly, I get overflow errors from the *2 statement but not
>> from self+self.
>
>How can you tell?  Your above example gives you no way to tell what
>line you get an overflow on.  And the way it's written, if you got an
>overflow on X := X*2, the exception would take you out of the loop and
>you'd never get to the p := p+p statement for the same value (since it
>looks like X=n=p will always be true at the beginning of the loop).
>

Ok.  I got this example from the online tutorial and I kept modifying
it to try something new.  Before I experimented w/  exception
handling, I was getting constraint_error exceptions.  

But Jeff Carter above explained that was I was seeing was really range
checking effects and not overflow effects.  That helped me understand
what was going on.




^ permalink raw reply	[relevance 0%]

* Re: float confusion
  2009-07-14 22:46  5% float confusion Rob Solomon
  2009-07-14 23:26  0% ` Randy Brukardt
@ 2009-07-14 23:50  0% ` Adam Beneschan
  2009-07-15  0:03  0%   ` Rob Solomon
  1 sibling, 1 reply; 200+ results
From: Adam Beneschan @ 2009-07-14 23:50 UTC (permalink / raw)


On Jul 14, 3:46 pm, Rob Solomon <use...@drrob1-noreply.com> wrote:
> I ran this simple example thru GNAT and I'm confused by the result.
>
> -- conclusions from this pgm
> -- integer type does not raise overflow constraint_error
> -- natural and positive types do raise overflow constraint_error when
> -- overflow is by multiplication, but not by addition.
>
> with Ada.Text_IO;
> with Ada.Integer_Text_IO;
> with Ada.Float_Text_IO;
> use Ada.Text_IO;
> use Ada.Integer_Text_IO;
> use Ada.Float_Text_IO;
>
>    procedure SimpleCompute is
>
>    X : Integer := 1;
>    c : Integer := 0;  -- counter
>    N : Natural := 1;
>    P : Positive := 1;
>    F : Float := 1.0;
>
>    begin
>    put_line("X C N P F");
>    loop
>     put(X);
>     card32_IO.put(u2);
>     put(c,3);
>     put(n);
>     put(' ');
>     put(p);
>     put(' ');
>     put(f,15,0,0);
>     New_Line;
>     X := X * 2;
>     n := n * 2;
>     p := p + p;
>     f := f * 2.0;
>     c := c +1;
>     exit when c > 40;
>    end loop;
>    exception
>       when constraint_error =>
>          n := 1;
>    end simplecompute;
>
> My confusion is that float'digits is 6 and long_float'digits is 15 (I
> already checked this).
>
> When I run this code, float grows to the full 13 digits before I stop
> it.  Why is that?

It only appears to.  Put(f,15,0,0) will display as many digits as it
needs to to display the integer part of "f", since you told it not to
display in exponential notation.  Float'Digits is 6, which means you
can count on the float having 6 significant decimal digits.  Any other
decimal digits you see, past the first 6 or 7, will be, in essence,
garbage.  But the Put routine has to display something for those
digits.

The results happen to be correct, but that's only because you're
computing powers of 2, which means that if Put assumes that any bits
dropped of the end of the float are 0, it will be correct.  If you try
modifying the code to do this:

   f := f * 2.0;
   if c > 20 then f := f - 1.0; end if;

you'll see that after f gets to about seven or eight significant
digits, the results will start being wrong, because the 1.0 that
you're trying to subtract will become too small for a float whose
'digits is only 6.

I hope that helps explain things; if you need to know more, you'll
need to start looking into the details of how IEEE 32-bit floats are
implemented.


> And interestingly, I get overflow errors from the *2 statement but not
> from self+self.

How can you tell?  Your above example gives you no way to tell what
line you get an overflow on.  And the way it's written, if you got an
overflow on X := X*2, the exception would take you out of the loop and
you'd never get to the p := p+p statement for the same value (since it
looks like X=n=p will always be true at the beginning of the loop).

                                -- Adam



^ permalink raw reply	[relevance 0%]

* Re: float confusion
  2009-07-14 22:46  5% float confusion Rob Solomon
@ 2009-07-14 23:26  0% ` Randy Brukardt
  2009-07-14 23:50  0% ` Adam Beneschan
  1 sibling, 0 replies; 200+ results
From: Randy Brukardt @ 2009-07-14 23:26 UTC (permalink / raw)


Did you use -gnato? Gnat doesn't check integer overflow by default (one of 
the worst design decisions in GNAT, IMHO.)

If you are just starting out, you ought to use -gnato -fstack_check on all 
of your compilations in order to get the behavior specified by the standard. 
(To be perfectly like the Ada Standard, you also need to use -gnatE, but 
that is much less likely to cause trouble.)

                                    Randy.

"Rob Solomon" <usenet@drrob1-noreply.com> wrote in message 
news:sc2q55185rv4dhc8dk0feu0dvuq7887oul@4ax.com...
>I ran this simple example thru GNAT and I'm confused by the result.
>
> -- conclusions from this pgm
> -- integer type does not raise overflow constraint_error
> -- natural and positive types do raise overflow constraint_error when
> -- overflow is by multiplication, but not by addition.
>
> with Ada.Text_IO;
> with Ada.Integer_Text_IO;
> with Ada.Float_Text_IO;
> use Ada.Text_IO;
> use Ada.Integer_Text_IO;
> use Ada.Float_Text_IO;
>
>
>   procedure SimpleCompute is
>
>   X : Integer := 1;
>   c : Integer := 0;  -- counter
>   N : Natural := 1;
>   P : Positive := 1;
>   F : Float := 1.0;
>
>   begin
>   put_line("X C N P F");
>   loop
>    put(X);
>    card32_IO.put(u2);
>    put(c,3);
>    put(n);
>    put(' ');
>    put(p);
>    put(' ');
>    put(f,15,0,0);
>    New_Line;
>    X := X * 2;
>    n := n * 2;
>    p := p + p;
>    f := f * 2.0;
>    c := c +1;
>    exit when c > 40;
>   end loop;
>   exception
>      when constraint_error =>
>         n := 1;
>   end simplecompute;
>
> My confusion is that float'digits is 6 and long_float'digits is 15 (I
> already checked this).
>
> When I run this code, float grows to the full 13 digits before I stop
> it.  Why is that?
>
> And interestingly, I get overflow errors from the *2 statement but not
> from self+self.  I wonder if this occurs because this kind of overflow
> is needed in the computation of random numbers.
>
> Thx 





^ permalink raw reply	[relevance 0%]

* float confusion
@ 2009-07-14 22:46  5% Rob Solomon
  2009-07-14 23:26  0% ` Randy Brukardt
  2009-07-14 23:50  0% ` Adam Beneschan
  0 siblings, 2 replies; 200+ results
From: Rob Solomon @ 2009-07-14 22:46 UTC (permalink / raw)


I ran this simple example thru GNAT and I'm confused by the result.

-- conclusions from this pgm
-- integer type does not raise overflow constraint_error
-- natural and positive types do raise overflow constraint_error when
-- overflow is by multiplication, but not by addition.

with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Float_Text_IO;
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use Ada.Float_Text_IO;


   procedure SimpleCompute is

   X : Integer := 1;
   c : Integer := 0;  -- counter
   N : Natural := 1;
   P : Positive := 1;
   F : Float := 1.0;

   begin
   put_line("X C N P F");
   loop
    put(X);
    card32_IO.put(u2);
    put(c,3);
    put(n);
    put(' ');
    put(p);
    put(' ');
    put(f,15,0,0);
    New_Line;
    X := X * 2;
    n := n * 2;
    p := p + p;
    f := f * 2.0;
    c := c +1;
    exit when c > 40;
   end loop;
   exception
      when constraint_error =>
         n := 1;
   end simplecompute;

My confusion is that float'digits is 6 and long_float'digits is 15 (I
already checked this).

When I run this code, float grows to the full 13 digits before I stop
it.  Why is that?

And interestingly, I get overflow errors from the *2 statement but not
from self+self.  I wonder if this occurs because this kind of overflow
is needed in the computation of random numbers.

Thx



^ permalink raw reply	[relevance 5%]

* Re: getting back to null range
  2009-07-09 23:10  4% getting back to null range anon
@ 2009-07-12 18:20  4% ` AdaMagica
  0 siblings, 0 replies; 200+ results
From: AdaMagica @ 2009-07-12 18:20 UTC (permalink / raw)


This is an excerpt (and slightly modified) of what anon proposed as a
test program.
----
with Ada.Integer_Text_IO ;
with Ada.Text_IO ;

use Ada.Integer_Text_IO ;
use Ada.Text_IO ;

procedure t is

  -- Display String values, with a title

  procedure Put ( T : String ; B : String ) is

    begin
      Put ( T ) ;
      Put ( "'( " ) ;
      Put ( B'First ) ;
      Put ( " .. " ) ;
      Put ( B'Last ) ;
      Put ( " ) => " ) ;
      Put ( B ) ;
      Put ( ", Length => " ) ;
      Put ( B'length ) ;
      New_Line;
    end Put ;

  A : Positive range -5 .. -7 ; -- Value is a nul range
                                -- Creates the compiler warning
message

begin

  declare
    --  Without these pragma statements the following declaration
    --  statement will compile but generates an C_E at run time
--      pragma Suppress ( Index_Check ) ;
--      pragma Suppress ( Range_Check ) ;

    S_B : String := ( A => 'Z' ) ; -- should be equal to S_A

  begin
    Put (A);  Put (A'Size);  New_Line;
    Put ( "null S_B", S_B ) ;
  end ;

end t ;
---
I do not understand what (s)he want's to prove with this piece of
code.

The declaration of A produces a warning, because it is read but never
assigned. His (her) assertion that the value is a null range is wrong.
A value is *never* a range. The subtype of A is a null range so that
one cannot assign any value to A. But nevertheless A exists and has a
size and an address and there is some random sequence of bits at that
address which can be interpreted as an integer.

My result is:
    4201563         32
null S_B'(     4201563 ..     4201563 ) => Z, Length =>           1

anon got an exception without pragma Suppress because in his case A
had the sequence of bit that interpreted as integer was 0, which is
not in range of Positive. So the exception is appropriate. If (s)he
suppresses the check, the program is erroneous if the check would have
failed. So what does (s)he prove with an erroneous program?

In my case, the value is in Positive, so no exception.

And of course S_B is not a null string because it is initialized with
an aggregate that has a value (albeit a random one).

For any integers A, B such that the following is legal

  X: String := (A..B => something);  -- A..B is a range (might be a
null range)

is not the same as

  X: String := (A => something);  -- an aggregate with one component
(if A in Positive)



^ permalink raw reply	[relevance 4%]

* getting back to null range
@ 2009-07-09 23:10  4% anon
  2009-07-12 18:20  4% ` AdaMagica
  0 siblings, 1 reply; 200+ results
From: anon @ 2009-07-09 23:10 UTC (permalink / raw)




with Ada.Integer_Text_IO ;
with Ada.Text_IO ;

use Ada.Integer_Text_IO ;
use Ada.Text_IO ;

procedure t is

  -- Display String values, with a title

  procedure Put ( T : String ; B : String ) is

    begin
      Put ( T ) ;
      Put ( "'( " ) ;
      Put ( B'First ) ;
      Put ( " .. " ) ;
      Put ( B'Last ) ;
      Put ( " ) => " ) ;
      Put ( B'length ) ;
      Put ( " => " ) ;
      Put_Line ( B ) ;
    end Put ;


  N : String := "" ;
  S : String := ( "123456789" ) ;

  --  From GNAT "Feature-316" file.
  --
  --    NF-316-B412-009 Warning on values for null ranges
  --
  --      If the compiler knows that a range is null, then it knows 
  --      that no value can conform to the range and that 
  --      Constraint_Error will be raised. A warning is now generated 
  --      in this situation.

  A : Positive range -5 .. -7 ; -- Value is a nul range
                                -- Creates the compiler warning message

  --
  -- A null string
  --
  S_A : String := ( -5 .. -7 => 'Z' ) ;


  subtype B is Positive range 9 .. 7 ;
  subtype C is Positive range 7 .. 5 ;

  S_R : String := ( C => 'Y' ) ;


begin
  Put ( "N", N ) ;
  Put ( "S", S ) ;
  Put ( "null S", S ( -5 ..-7 ) ) ;
  New_Line ;

  Put ( "null S_A", S_A ) ;
  if N = S_A then 
    Put_Line ( "N equal S_A" ) ;
  else
    Put_Line ( "N not equal S_A" ) ;
  end if ;

  declare
    --  Without these pragma statements the following declaration 
    --  statement will compile but generates an C_E at run time
    pragma Suppress ( Index_Check ) ;    
    pragma Suppress ( Range_Check ) ;

    S_B : String := ( A => 'Z' ) ; -- should be equal to S_A 

  begin
    Put ( "null S_B", S_B ) ;  
    if N = S_B then                -- Gives,  N not equal S_B
      Put_Line ( "N equal S_B" ) ;
    else
      Put_Line ( "N not equal S_B" ) ;
    end if ;

    if S_A = S_B then              -- Gives, S_A not equal S_B
      Put_Line ( "S_A equal S_B" ) ;
    else
      Put_Line ( "S_A not equal S_B" ) ;
    end if ;
  end ;

  Put ( "null S_R ", S_R ) ;
  Put ( "null S_R ", S_R ( B ) ) ;

  if S_R = S_R ( B ) then 
    Put_Line ( "S_R equal S_R ( B )" ) ;
  else
    Put_Line ( "S_R not equal S_R ( B )" ) ;
  end if ;

  begin
    --
    -- will result in a C_E when ( Index - 5 ) is no longer Positive 
    -- aka ( Index - 5 ) < 1 , It seams that the upper bound can be 
    -- a legal positive or not
    --
    Put_Line ( "Scanning an String:  Upper bound Postive" ) ;
    for Index in reverse S'Range loop
      Put ( "Reverse S", S ( ( Index - 5 ).. 6 ) ) ;
    end loop ;
  exception 
    when Constraint_Error =>
     Put_Line ( "Constraint_Error: Lower bound < 1" ) ;
     null ;
  end ;
  New_Line ;

  -- checking when upper bound is not a legal member of the script type
  -- Should result in an error at the same index value as previous 
  -- block statements. but does not!
  begin
    Put_Line ( "Scanning with Upper bound swaping Negative" ) ;
    for Index in reverse S'Range loop
      begin
        Put ( "Neg S", S ( ( Index - 5 ) .. ( Index - 11 ) ) ) ;
      exception
        when Constraint_Error =>
          Put_Line ( "Constraint_Error: " & 
                   Integer'Image ( Index ) & " ( " &
                   Integer'Image ( Index - 5 ) & " .. " &
                   Integer'Image ( Index - 11 ) & " )" ) ;
          exit ;
      end ;
      --
      begin
        Put ( "    S", S ( ( Index - 5 ) .. ( Index - 4 ) ) ) ;
      exception
        when Constraint_Error =>
          Put_Line ( "Constraint_Error: " &
                   Integer'Image ( Index ) & " ( " &
                   Integer'Image ( Index - 5 ) & " .. " &
                   Integer'Image ( Index - 4 ) & " )" ) ;
          exit ;
      end ;
    end loop ;
  end ;
  New_line ;
end t ;




^ permalink raw reply	[relevance 4%]

* Re: unsigned type
  2009-07-02 19:49  4%   ` anon
@ 2009-07-03  1:42  0%     ` anon
  0 siblings, 0 replies; 200+ results
From: anon @ 2009-07-03  1:42 UTC (permalink / raw)


--
-- Just a side note.   Found while using a search engine.
--
with Ada.Text_IO ;
use  Ada.Text_IO ;

procedure Temp is

    C : constant String := ( 1..0 => 'A' ) ; 
    --
    --  So, what happens to the 'A' and why does the compiler allow 
    --  the constant 'A' when it result will be a null array.
    --
    --  If you use ( 1..0 => 'A' ) you must provide an unusable single
    --  Character, double quotes or emply quote are illegal.  Logic 
    --  suggest that the statement should be
    --  C : constant String := ( 1..0 => '' ) ;
    --
    D : constant String := "" ; 

begin

  Put_line ( "C => '" & C & "'  =  '" & C ( 1..0 ) & "'" ) ;
  New_Line ;

  Put_Line ( "is C equal to D => " & Boolean'Image ( C = D ) ) ;
  New_Line ;
 
end Temp ;


In <4b83m.98382$d36.15650@bgtnsc04-news.ops.worldnet.att.net>, anon@anon.org (anon) writes:
>--  Adam. 
>--    Now, can you please explain the results from this program.
>--
>--    It just does not make sense.  Because in the second pass though  
>--    Test.Put the bounds for String is ( 1..1 ) but if the procedure 
>--    uses a String ( 2 .. -2 ) which neither index is not within the 
>--    valid subscript range. And this is also echoed in the third pass.
>--
>--    Note: The RM uses ( 1 .. 0 ) but allows ( L .. R ) if L > R, for
>--           null arrays.  But I think the RM and ACATS suggest that the 
>--           Left side index needs to be a valid subscript of the array.
>--           Which make B ( 2 .. -2 ) illegal if the B String is bound
>--           by ( 1 .. 1 ).
>--
>with Ada.Integer_Text_IO ;
>with Ada.Text_IO ;
>with Ada.Exceptions ;
>
>procedure Test is
>
>  use Ada.Exceptions ;
>  use Ada.Integer_Text_IO ;
>  use Ada.Text_IO ;
>
>  C : String := "This is a test string" ;
>
>  --
>  -- Define a Put routine for String type.
>  --
>  procedure Put ( B : String ) is
>
>    begin
>      New_Line ;
>      Ada.Text_IO.Put ( "    B'( " ) ;
>      Put ( B'First ) ;
>      Ada.Text_IO.Put ( " .. " ) ;
>      Put ( B'Last ) ;
>      Ada.Text_IO.Put ( " ) => " ) ;
>      Ada.Text_IO.Put_Line ( ( B ( B'First .. B'Last ) ) ) ;
>
>      Ada.Text_IO.Put ( "    B'( 2 .. -2 ) => '" ) ;
>      Ada.Text_IO.Put ( ( B ( 2 .. -2 ) ) ) ;
>      Ada.Text_IO.Put ( ''' ) ;
>      New_Line ( 2 ) ;
>    end Put ;
>
>begin
>
>  Ada.Text_IO.Put_line ( "Normal String Print  --  Valid" ) ;
>  Ada.Text_IO.Put ( "C ( C'First .. C'Last ) => " ) ;
>  begin
>    Test.Put ( C ( C'First .. C'Last ) ) ;
>  exception
>    when E : Constraint_Error =>
>      Ada.Text_IO.Put_Line ( Exception_Name ( E ) & 
>                             " => " &
>                             Exception_Message ( E ) ) ;
>  end ;
>  New_Line ;
>
>  Ada.Text_IO.Put_line ( "Normal Sub String Print  --  Invalid???" ) ;
>  Ada.Text_IO.Put ( "C ( C'First .. C'First ) => " ) ;
>  begin
>    Test.Put ( C ( C'First .. C'First ) ) ;
>  exception
>    when E : Constraint_Error =>
>      Ada.Text_IO.Put_Line ( Exception_Name ( E ) & 
>                             " => " &
>                             Exception_Message ( E ) ) ;
>  end ;
>  New_Line ;
>
>
>  Ada.Text_IO.Put_line ( "Normal Sub String Print  --  Invalid???" ) ;
>  Ada.Text_IO.Put ( "C ( ( C'First + 4 ) .. ( C'Last - 4 ) ) => " ) ;
>  begin
>    Test.Put ( C ( ( C'First + 4 ) .. ( C'Last - 4 ) ) ) ;
>  exception
>    when E : Constraint_Error =>
>      Ada.Text_IO.Put_Line ( Exception_Name ( E ) & 
>                             " => " &
>                             Exception_Message ( E ) ) ;
>  end ;
>  New_Line ;
>
>end Test ;
>
>In <273dedb7-8d68-42d2-8602-aa44c79f3708@b9g2000yqm.googlegroups.com>, Adam Beneschan <adam@irvine.com> writes:
>>On Jun 30, 4:48=A0pm, a...@anon.org (anon) wrote:
>>> Read RM 3.5 =A0( 4 )
>>>
>>> Is "A ( 0 .. 0 )" an example of null range. =A0By the definition in RM 3.=
>>5
>>> ( 4 ), the Right side range (index) must be less than the Left side, so
>>> "A ( 0.. 0 )" is not a valid null range statement. So, this statement
>>> should generate a compiler or runtime error, because either range is not
>>> a subset of the range for Strings.
>>
>>OK, I think I've finally figured out why we're having this confusing
>>argument.  It goes way back to this post of yours:
>>
>>>> For Strings:
>>>>                          --  'A' is a zero length string, A'Last =3D 0, =
>>and
>>>>                          --  put_line  ( A ( A'First .. A'Last ) ) ;
>>>>                          --  does not raise an Constraint_Error even tho=
>>ugh in
>>>>                          --  this case it translate to:
>>>>                          --  put_line  ( A ( 0 .. 0 ) ) ;
>>>>  A : String :=3D ""        ;
>>
>>It does not translate to A (0..0); it translates to A (1..0).  If A is
>>declared as in your example above, A'First will be 1 and A'Last will
>>be 0.  Try it (try declaring A like that and outputting A'First and
>>A'Last).  It looks like everyone else missed this original error of
>>yours, which has apparently led to some confusion.
>>
>>In this case, A'First..A'Last, which is 1..0, is compatible with the
>>subtype because it's a null range, and null ranges are compatible with
>>the subtype even when the range bounds don't actually belong to the
>>subtype.  0..0 is not compatible with the subtype, but you cannot
>>declare a string with that index range unless you try to do it
>>explicitly:
>>
>>   A : String (0..0);
>>
>>and then you *will* get a Constraint_Error.
>>
>>So your later assertion that follows:
>>
>>>> Since you can have zero length string , the index is Natual instead of P=
>>ositive,
>>>> because zero is in Natural but is not define in Positive. Even though th=
>>e
>>>> Standard package define String index as a Positive type. (GNAT)
>>
>>is wrong.  The index range is Positive, but null ranges don't have to
>>meet that constraint.  They don't have to be Natural, either.  This is
>>legal and will not raise an exception at runtime:
>>
>>   B : String (-9 .. -10) :=3D "";
>>
>>Hope this clears everything up.
>>
>>                                  -- Adam
>>
>




^ permalink raw reply	[relevance 0%]

* Re: unsigned type
  @ 2009-07-02 19:49  4%   ` anon
  2009-07-03  1:42  0%     ` anon
  0 siblings, 1 reply; 200+ results
From: anon @ 2009-07-02 19:49 UTC (permalink / raw)


--  Adam. 
--    Now, can you please explain the results from this program.
--
--    It just does not make sense.  Because in the second pass though  
--    Test.Put the bounds for String is ( 1..1 ) but if the procedure 
--    uses a String ( 2 .. -2 ) which neither index is not within the 
--    valid subscript range. And this is also echoed in the third pass.
--
--    Note: The RM uses ( 1 .. 0 ) but allows ( L .. R ) if L > R, for
--           null arrays.  But I think the RM and ACATS suggest that the 
--           Left side index needs to be a valid subscript of the array.
--           Which make B ( 2 .. -2 ) illegal if the B String is bound
--           by ( 1 .. 1 ).
--
with Ada.Integer_Text_IO ;
with Ada.Text_IO ;
with Ada.Exceptions ;

procedure Test is

  use Ada.Exceptions ;
  use Ada.Integer_Text_IO ;
  use Ada.Text_IO ;

  C : String := "This is a test string" ;

  --
  -- Define a Put routine for String type.
  --
  procedure Put ( B : String ) is

    begin
      New_Line ;
      Ada.Text_IO.Put ( "    B'( " ) ;
      Put ( B'First ) ;
      Ada.Text_IO.Put ( " .. " ) ;
      Put ( B'Last ) ;
      Ada.Text_IO.Put ( " ) => " ) ;
      Ada.Text_IO.Put_Line ( ( B ( B'First .. B'Last ) ) ) ;

      Ada.Text_IO.Put ( "    B'( 2 .. -2 ) => '" ) ;
      Ada.Text_IO.Put ( ( B ( 2 .. -2 ) ) ) ;
      Ada.Text_IO.Put ( ''' ) ;
      New_Line ( 2 ) ;
    end Put ;

begin

  Ada.Text_IO.Put_line ( "Normal String Print  --  Valid" ) ;
  Ada.Text_IO.Put ( "C ( C'First .. C'Last ) => " ) ;
  begin
    Test.Put ( C ( C'First .. C'Last ) ) ;
  exception
    when E : Constraint_Error =>
      Ada.Text_IO.Put_Line ( Exception_Name ( E ) & 
                             " => " &
                             Exception_Message ( E ) ) ;
  end ;
  New_Line ;

  Ada.Text_IO.Put_line ( "Normal Sub String Print  --  Invalid???" ) ;
  Ada.Text_IO.Put ( "C ( C'First .. C'First ) => " ) ;
  begin
    Test.Put ( C ( C'First .. C'First ) ) ;
  exception
    when E : Constraint_Error =>
      Ada.Text_IO.Put_Line ( Exception_Name ( E ) & 
                             " => " &
                             Exception_Message ( E ) ) ;
  end ;
  New_Line ;


  Ada.Text_IO.Put_line ( "Normal Sub String Print  --  Invalid???" ) ;
  Ada.Text_IO.Put ( "C ( ( C'First + 4 ) .. ( C'Last - 4 ) ) => " ) ;
  begin
    Test.Put ( C ( ( C'First + 4 ) .. ( C'Last - 4 ) ) ) ;
  exception
    when E : Constraint_Error =>
      Ada.Text_IO.Put_Line ( Exception_Name ( E ) & 
                             " => " &
                             Exception_Message ( E ) ) ;
  end ;
  New_Line ;

end Test ;

In <273dedb7-8d68-42d2-8602-aa44c79f3708@b9g2000yqm.googlegroups.com>, Adam Beneschan <adam@irvine.com> writes:
>On Jun 30, 4:48=A0pm, a...@anon.org (anon) wrote:
>> Read RM 3.5 =A0( 4 )
>>
>> Is "A ( 0 .. 0 )" an example of null range. =A0By the definition in RM 3.=
>5
>> ( 4 ), the Right side range (index) must be less than the Left side, so
>> "A ( 0.. 0 )" is not a valid null range statement. So, this statement
>> should generate a compiler or runtime error, because either range is not
>> a subset of the range for Strings.
>
>OK, I think I've finally figured out why we're having this confusing
>argument.  It goes way back to this post of yours:
>
>>> For Strings:
>>>                          --  'A' is a zero length string, A'Last =3D 0, =
>and
>>>                          --  put_line  ( A ( A'First .. A'Last ) ) ;
>>>                          --  does not raise an Constraint_Error even tho=
>ugh in
>>>                          --  this case it translate to:
>>>                          --  put_line  ( A ( 0 .. 0 ) ) ;
>>>  A : String :=3D ""        ;
>
>It does not translate to A (0..0); it translates to A (1..0).  If A is
>declared as in your example above, A'First will be 1 and A'Last will
>be 0.  Try it (try declaring A like that and outputting A'First and
>A'Last).  It looks like everyone else missed this original error of
>yours, which has apparently led to some confusion.
>
>In this case, A'First..A'Last, which is 1..0, is compatible with the
>subtype because it's a null range, and null ranges are compatible with
>the subtype even when the range bounds don't actually belong to the
>subtype.  0..0 is not compatible with the subtype, but you cannot
>declare a string with that index range unless you try to do it
>explicitly:
>
>   A : String (0..0);
>
>and then you *will* get a Constraint_Error.
>
>So your later assertion that follows:
>
>>> Since you can have zero length string , the index is Natual instead of P=
>ositive,
>>> because zero is in Natural but is not define in Positive. Even though th=
>e
>>> Standard package define String index as a Positive type. (GNAT)
>
>is wrong.  The index range is Positive, but null ranges don't have to
>meet that constraint.  They don't have to be Natural, either.  This is
>legal and will not raise an exception at runtime:
>
>   B : String (-9 .. -10) :=3D "";
>
>Hope this clears everything up.
>
>                                  -- Adam
>




^ permalink raw reply	[relevance 4%]

* Re: unsigned type
  @ 2009-06-29 15:37  3%     ` Adam Beneschan
  0 siblings, 0 replies; 200+ results
From: Adam Beneschan @ 2009-06-29 15:37 UTC (permalink / raw)


On Jun 29, 6:36 am, Rob Solomon <use...@drrob1-noreply.com> wrote:
> I was able to use the Natural and Positive.  
>
> Now I'm trying to understand Mod types.
>
> I tried this:
> type card31 is mod 2_147_483_648;
> type card32 is mod 4_294_967_296;
> c31 : Card31;
> c32: Card32;
> LI : Long_Integer;
> and
>
> LI := Long_Integer(c32);
>
> How to I output c31 and c32?  Modula-2 uses WriteCard or CardToString
> and WriteString
>
> I tried using Put, but I got an error saying that correct procedure
> could not be found, or something like that.
>
> Put(LI) works until the value of LI > 2**31, even for c32.

Ada is a strongly typed language.  "Integer" is a type (defined by the
language); but whenever you declare a new type with a "type" statement
(whether it's a modular type, another signed integer type, or
something else), it will be a new type, and you can't automatically
use values of this new type in places where a value of type Integer is
expected.  The advantage of this is that you can define types for
separate purposes, so that if you declare a real type "Distance" and
another real type "Velocity", for example, you can't accidentally use
a Distance value as a parameter to a procedure that wants a Velocity,
e.g.

The "Put" routine you're using is probably from the
Ada.Integer_Text_IO package; that routine needs an Integer parameter
and won't accept a value of any other type, even another integer
type.  You can create a Put routine that accepts a value of the type
you want by generic instantiation.  For a modular type, an instance of
Ada.Text_IO.Modular_IO (see Georg's post) will create a new package
that has a Put routine with the right parameter type.

The strong typing aspect of Ada is something that trips up a lot of
new Ada programmers, so it's something that I think you do need to
understand.  I don't know Modula-2 so I don't know whether this
concept is already familiar to you.

                                            -- Adam





^ permalink raw reply	[relevance 3%]

* Re: BASIC_NUM_IO
  @ 2009-06-01  8:18  6% ` anon
  0 siblings, 0 replies; 200+ results
From: anon @ 2009-06-01  8:18 UTC (permalink / raw)


"Ada.Integer_Text_IO" is the standard package that most use for integer I/O

with Ada.Text_IO ;   -- use for "new_line" 
use  Ada.Text_IO ;

with Ada.Integer_Text_IO ; -- use for integer "put" 
use  Ada.Integer_Text_IO ;

procedure test_ranges is
begin
  put ( short_integer'size ) ;
  new_line ;
end test_ranges ;


If you want to define your own type of integer  then 

with Ada.Text_IO ;   -- use for new_line 
use  Ada.Text_IO ;

procedure test_ranges is

  package basic_num_io is new Ada.Text_IO.Integer_IO ( Integer ) ;
  use basic_num_io ; 

begin
  put ( short_integer'size ) ;
  new_line ;
end test_ranges ;

In <78hfulF1m321pU2@mid.individual.net>, Georg <nobody@nowhere.com> writes:
>Hi All,
>
>in my Ada books I find the with-clause "with BASIC_NUM_IO; use 
>BASIC_NUM_IO".
>
>The following program
>
>with basic_num_io; use basic_num_io;
>
>procedure test_ranges is
>begin
>   put_line(short_integer'size);
>end test_ranges;
>
>does not compile because the compiler complaints that the package 
>"basic_num_io" does not exist.
>
>Is there a replacement for this package in GNAT? How can I print number 
>on the screen instead?
>
>Regards
>
>Georg




^ permalink raw reply	[relevance 6%]

* Re: How it works get_line function
  @ 2009-05-09 20:56  5%   ` juanmiuk
  0 siblings, 0 replies; 200+ results
From: juanmiuk @ 2009-05-09 20:56 UTC (permalink / raw)


Hello Jeffrey,

First of all say thank you for you help. I got it, and I wrote a
program for show you:

with Ada.Text_Io;		use Ada.Text_Io;
with Ada.Integer_Text_IO;	use Ada.Integer_Text_IO;

procedure Read_String_func_1 is

begin
	Put ("Type a String: ");
	declare
	    Cadena : Constant String := Get_Line;
	begin
		Put("You typed: " & Cadena);
	end;

	New_Line;

	Put("Type a Integer: ");
	declare
		Input : Constant String := Get_Line;
		Num   : Natural;
	begin
		Num := Natural'Value(Input);
		Put ("You typed :" );
		Put(Num, 6);
		New_Line;
		Put("Converted with Natural'Image is: " & Natural'Image(Num));
	end;

end Read_String_Func_1;
On 8 May, 22:33, "Jeffrey R. Carter"
<spam.jrcarter....@nospam.acm.org> wrote:
> juanmiuk wrote:
> > with Ada.Text_Io;
> > use Ada.Text_Io;
>
> > procedure Read_String_func is
> >    Line : String (1 .. 80);
> > begin
> >    Put("Write a string: ");
> >    Line := Get_Line;
> > end Read_String_Func;
>
> > Write a string: adfkjadfk
>
> > raised CONSTRAINT_ERROR : read_string_func.adb:11 length check failed
>
> > What I was doing wrong?
>
> You were attempting to assign a 9-Character String to an 80-Character String.
> When assigning arrays, both sides need to be the same size.
>
> The Get_Line function is best suited to initializing a String object, or
> providing a value to another subprogram:
>
> S1 : constant String := Ada.Text_IO.Get_Line;
>
> S2 : String := Ada.Text_IO.Get_Line;
>
> Ada.Text_IO.Put_Line (Item => Ada.Text_IO.Get_Line);
>
> --
> Jeff Carter
> "I like it when the support group complains that they have
> insufficient data on mean time to repair bugs in Ada software."
> Robert I. Eachus
> 91




^ permalink raw reply	[relevance 5%]

* Re: Problem with optimizations
  2009-04-28 19:15  0%     ` Olivier Scalbert
  2009-04-29 10:36  0%       ` johnscpg
  2009-04-29 10:45  0%       ` johnscpg
@ 2009-04-29 13:51  0%       ` johnscpg
  2 siblings, 0 replies; 200+ results
From: johnscpg @ 2009-04-29 13:51 UTC (permalink / raw)


On Apr 28, 8:15 pm, Olivier Scalbert <olivier.scalb...@algosyn.com>
wrote:
> Albrecht Käfer wrote:
> > (see below) schrieb::
> >> There is no else part for the following if:
>
> >>             if Is_Solved(Cube) then
> >>                 New_Line;
> >>                 Put("Solved !"); New_Line;
>
> >>                 for i in 1..depth-1 loop
> >>                     Ada.Integer_Text_IO.Put(Integer(Moves(i)));
> >>                 end loop;
> >>                 Result := True;
> >>             end if;
>
> >> So the procedure can exit with Result undefined. Since the program is
> >> incorrect, varying optimisation, or implementation details, is likely to
> >> give varying results. Some may co-incidentally be the results you expect.
>
> > Shouldn't that, you know, create a warning or something?
>
> > Albrecht
>
> That is what I was thinking, but with:
>
> gnatmake -f -O3 -W -gnatp rubikmain
>
> it detects the bug (and also an other one in the same function)
>
> Shame on me !

I also learned this recently using gfortran.
You need the -O flag along with the -W to
get the gcc compiler to report uninitialized
variables.  As you've shown, it spots possible
uninitialized variables in  if-then-else
blocks or for-loops.  It mostly speculates - its
usually wrong, but I like it. In gfortran
you can limit the -W with: -O -Wuninitialized.
Don't know about gnatmake, but
gnatmake  accepts it.

cheers
jonathan

(This will be my 3rd and final attempt to post this -
hope 3 of these posts don't eventually appear,
but I can't seem to get gmail to let me through.
It sure likes spam tho' ;)



^ permalink raw reply	[relevance 0%]

* Re: Problem with optimizations
  2009-04-28 19:15  0%     ` Olivier Scalbert
  2009-04-29 10:36  0%       ` johnscpg
@ 2009-04-29 10:45  0%       ` johnscpg
  2009-04-29 13:51  0%       ` johnscpg
  2 siblings, 0 replies; 200+ results
From: johnscpg @ 2009-04-29 10:45 UTC (permalink / raw)


On Apr 28, 8:15 pm, Olivier Scalbert <olivier.scalb...@algosyn.com>
wrote:
> Albrecht Käfer wrote:
> > (see below) schrieb::
> >> There is no else part for the following if:
>
> >>             if Is_Solved(Cube) then
> >>                 New_Line;
> >>                 Put("Solved !"); New_Line;
>
> >>                 for i in 1..depth-1 loop
> >>                     Ada.Integer_Text_IO.Put(Integer(Moves(i)));
> >>                 end loop;
> >>                 Result := True;
> >>             end if;
>
> >> So the procedure can exit with Result undefined. Since the program is
> >> incorrect, varying optimisation, or implementation details, is likely to
> >> give varying results. Some may co-incidentally be the results you expect.
>
> > Shouldn't that, you know, create a warning or something?
>
> > Albrecht
>
> That is what I was thinking, but with:
>
> gnatmake -f -O3 -W -gnatp rubikmain
>
> it detects the bug (and also an other one in the same function)
>
> Shame on me !

I also learned this recently (using gfortran).   You have to have -O
to
get the -W to work when you are looking for uninitialized variables.
Exactly as you've shown, it flags variables that may or may not
be initialized in for loops, or if then else blocks.  Its usually
wrong,
(it speculates) but I like it.  In gfortan you can write -O -
Wuninitialized; probably
same with gnatmake (it accepts it anyway).

cheers,
jonathan



^ permalink raw reply	[relevance 0%]

* Re: Problem with optimizations
  2009-04-28 19:15  0%     ` Olivier Scalbert
@ 2009-04-29 10:36  0%       ` johnscpg
  2009-04-29 10:45  0%       ` johnscpg
  2009-04-29 13:51  0%       ` johnscpg
  2 siblings, 0 replies; 200+ results
From: johnscpg @ 2009-04-29 10:36 UTC (permalink / raw)


On Apr 28, 8:15 pm, Olivier Scalbert <olivier.scalb...@algosyn.com>
wrote:
> Albrecht Käfer wrote:
> > (see below) schrieb::
> >> There is no else part for the following if:
>
> >>             if Is_Solved(Cube) then
> >>                 New_Line;
> >>                 Put("Solved !"); New_Line;
>
> >>                 for i in 1..depth-1 loop
> >>                     Ada.Integer_Text_IO.Put(Integer(Moves(i)));
> >>                 end loop;
> >>                 Result := True;
> >>             end if;
>
> >> So the procedure can exit with Result undefined. Since the program is
> >> incorrect, varying optimisation, or implementation details, is likely to
> >> give varying results. Some may co-incidentally be the results you expect.
>
> > Shouldn't that, you know, create a warning or something?
>
> > Albrecht
>
> That is what I was thinking, but with:
>
> gnatmake -f -O3 -W -gnatp rubikmain
>
> it detects the bug (and also an other one in the same function)
>
> Shame on me !




^ permalink raw reply	[relevance 0%]

* Re: Problem with optimizations
  2009-04-28 19:12  0%     ` (see below)
@ 2009-04-29  2:35  0%       ` Gene
  0 siblings, 0 replies; 200+ results
From: Gene @ 2009-04-29  2:35 UTC (permalink / raw)


On Apr 28, 3:12 pm, "(see below)" <yaldni...@blueyonder.co.uk> wrote:
> On 28/04/2009 20:06, in article 49f753b9$0$2861$ba620...@news.skynet.be,
>
>
>
>
>
> "Olivier Scalbert" <olivier.scalb...@algosyn.com> wrote:
> > (see below) wrote:
>
> >> There is no else part for the following if:
>
> >>             if Is_Solved(Cube) then
> >>                 New_Line;
> >>                 Put("Solved !"); New_Line;
>
> >>                 for i in 1..depth-1 loop
> >>                     Ada.Integer_Text_IO.Put(Integer(Moves(i)));
> >>                 end loop;
> >>                 Result := True;
> >>             end if;
>
> >> So the procedure can exit with Result undefined. Since the program is
> >> incorrect, varying optimisation, or implementation details, is likely to
> >> give varying results. Some may co-incidentally be the results you expect.
>
> >> P.S. I did not use gdb.
>
> > You are right !
>
> > So an Ada compiler can compile incorrect programs !
> > ;-)
>
> It has no alternative, thanks to Turing.
> 8-) | 8-(
>
> --
> Bill
> "To explain the unknown by the known is a logical procedure; to explain
> the known by the unknown is a form of theological lunacy." David Brooks- Hide quoted text -

Well... Thanks to God and/or nature, wherein Turing had some
insight...





^ permalink raw reply	[relevance 0%]

* Re: Problem with optimizations
  2009-04-28 19:05  0%   ` Albrecht Käfer
@ 2009-04-28 19:15  0%     ` Olivier Scalbert
  2009-04-29 10:36  0%       ` johnscpg
                         ` (2 more replies)
  0 siblings, 3 replies; 200+ results
From: Olivier Scalbert @ 2009-04-28 19:15 UTC (permalink / raw)


Albrecht K�fer wrote:
> (see below) schrieb::
>> There is no else part for the following if:
>>
>>             if Is_Solved(Cube) then
>>                 New_Line;
>>                 Put("Solved !"); New_Line;
>>
>>                 for i in 1..depth-1 loop
>>                     Ada.Integer_Text_IO.Put(Integer(Moves(i)));
>>                 end loop;
>>                 Result := True;
>>             end if;
>>
>> So the procedure can exit with Result undefined. Since the program is
>> incorrect, varying optimisation, or implementation details, is likely to
>> give varying results. Some may co-incidentally be the results you expect.
> 
> Shouldn't that, you know, create a warning or something?
> 
> 
> Albrecht

That is what I was thinking, but with:

gnatmake -f -O3 -W -gnatp rubikmain

it detects the bug (and also an other one in the same function)

Shame on me !



^ permalink raw reply	[relevance 0%]

* Re: Problem with optimizations
  2009-04-28 19:06  0%   ` Olivier Scalbert
@ 2009-04-28 19:12  0%     ` (see below)
  2009-04-29  2:35  0%       ` Gene
  0 siblings, 1 reply; 200+ results
From: (see below) @ 2009-04-28 19:12 UTC (permalink / raw)


On 28/04/2009 20:06, in article 49f753b9$0$2861$ba620e4c@news.skynet.be,
"Olivier Scalbert" <olivier.scalbert@algosyn.com> wrote:

> (see below) wrote:
> 
>> 
>> There is no else part for the following if:
>> 
>>             if Is_Solved(Cube) then
>>                 New_Line;
>>                 Put("Solved !"); New_Line;
>> 
>>                 for i in 1..depth-1 loop
>>                     Ada.Integer_Text_IO.Put(Integer(Moves(i)));
>>                 end loop;
>>                 Result := True;
>>             end if;
>> 
>> So the procedure can exit with Result undefined. Since the program is
>> incorrect, varying optimisation, or implementation details, is likely to
>> give varying results. Some may co-incidentally be the results you expect.
>> 
>> P.S. I did not use gdb.
>> 
> 
> You are right !
> 
> So an Ada compiler can compile incorrect programs !
> ;-)

It has no alternative, thanks to Turing.
8-) | 8-(

-- 
Bill
"To explain the unknown by the known is a logical procedure; to explain
the known by the unknown is a form of theological lunacy." David Brooks




^ permalink raw reply	[relevance 0%]

* Re: Problem with optimizations
  2009-04-28 18:40  3% ` (see below)
  2009-04-28 19:05  0%   ` Albrecht Käfer
@ 2009-04-28 19:06  0%   ` Olivier Scalbert
  2009-04-28 19:12  0%     ` (see below)
  1 sibling, 1 reply; 200+ results
From: Olivier Scalbert @ 2009-04-28 19:06 UTC (permalink / raw)


(see below) wrote:

> 
> There is no else part for the following if:
> 
>             if Is_Solved(Cube) then
>                 New_Line;
>                 Put("Solved !"); New_Line;
> 
>                 for i in 1..depth-1 loop
>                     Ada.Integer_Text_IO.Put(Integer(Moves(i)));
>                 end loop;
>                 Result := True;
>             end if;
> 
> So the procedure can exit with Result undefined. Since the program is
> incorrect, varying optimisation, or implementation details, is likely to
> give varying results. Some may co-incidentally be the results you expect.
> 
> P.S. I did not use gdb.
> 

You are right !

So an Ada compiler can compile incorrect programs !
;-)



^ permalink raw reply	[relevance 0%]

* Re: Problem with optimizations
  2009-04-28 18:40  3% ` (see below)
@ 2009-04-28 19:05  0%   ` Albrecht Käfer
  2009-04-28 19:15  0%     ` Olivier Scalbert
  2009-04-28 19:06  0%   ` Olivier Scalbert
  1 sibling, 1 reply; 200+ results
From: Albrecht Käfer @ 2009-04-28 19:05 UTC (permalink / raw)


(see below) schrieb::
> There is no else part for the following if:
>
>             if Is_Solved(Cube) then
>                 New_Line;
>                 Put("Solved !"); New_Line;
>
>                 for i in 1..depth-1 loop
>                     Ada.Integer_Text_IO.Put(Integer(Moves(i)));
>                 end loop;
>                 Result := True;
>             end if;
>
> So the procedure can exit with Result undefined. Since the program is
> incorrect, varying optimisation, or implementation details, is likely to
> give varying results. Some may co-incidentally be the results you expect.

Shouldn't that, you know, create a warning or something?


Albrecht



^ permalink raw reply	[relevance 0%]

* Re: Problem with optimizations
  @ 2009-04-28 18:40  3% ` (see below)
  2009-04-28 19:05  0%   ` Albrecht Käfer
  2009-04-28 19:06  0%   ` Olivier Scalbert
  0 siblings, 2 replies; 200+ results
From: (see below) @ 2009-04-28 18:40 UTC (permalink / raw)


On 28/04/2009 18:04, in article 49f73730$0$2850$ba620e4c@news.skynet.be,
"Olivier Scalbert" <olivier.scalbert@algosyn.com> wrote:

...
> When, inside the Recursive_Find_Solution, I replace Is_Solved by
> Is_Solved1, then it works in all cases.
> 
> I have try to understand what is happen with gdb and by having a look
> into the generated code, but without success.
> 
> I have the same behaviour with:
> - Ubuntu 8.10 32 bits (GNATMAKE 4.3.2)
> - Debian testing AMD 64bits (GNATMAKE 4.3.3)
> 
> The code can be found there:
> http://scalbert.dyndns.org/adarubik/
> 
> This small project is a really a toy but I would like to understand the
> problem.

There is no else part for the following if:

            if Is_Solved(Cube) then
                New_Line;
                Put("Solved !"); New_Line;

                for i in 1..depth-1 loop
                    Ada.Integer_Text_IO.Put(Integer(Moves(i)));
                end loop;
                Result := True;
            end if;

So the procedure can exit with Result undefined. Since the program is
incorrect, varying optimisation, or implementation details, is likely to
give varying results. Some may co-incidentally be the results you expect.

P.S. I did not use gdb.

-- 
Bill Findlay, <surname><forename> chez blueyonder.co.uk
"My own view on religion is that of Lucretius. I regard it as a disease born
of fear and as a source of untold misery to the human race." B. Russell




^ permalink raw reply	[relevance 3%]

* Re: Invade wikipedia!
  @ 2009-02-26 13:53  6%     ` Ivan Levashew
  0 siblings, 0 replies; 200+ results
From: Ivan Levashew @ 2009-02-26 13:53 UTC (permalink / raw)


Jean-Pierre Rosen wrote:

> Just use Integer_Text_IO, and forget about the stupid space.

xen:~/just_test OCTAGRAM$ nano aitio.adb
xen:~/just_test OCTAGRAM$ ada_mode
xen:~/just_test OCTAGRAM$ gnatmake aitio.adb
gcc -c aitio.adb
gnatbind -aO./ -C -I- -x aitio.ali
gnatlink aitio.ali -C --GCC=/usr/local/ada-build/friendly/gcc
xen:~/just_test OCTAGRAM$ ./aitio
 >>>          8<<<
xen:~/just_test OCTAGRAM$ cat aitio.adb
with Ada.Text_IO;
with Ada.Integer_Text_IO;

use Ada;

procedure AITIO is

begin
    Text_IO.Put (">>>");
    Integer_Text_IO.Put (8);
    Text_IO.Put_Line ("<<<");
end AITIO;
xen:~/just_test OCTAGRAM$


It's broken either! I know how to fix it:

xen:~/just_test OCTAGRAM$ nano aitio.adb
xen:~/just_test OCTAGRAM$ gnatmake aitio.adb
gcc -c aitio.adb
gnatbind -aO./ -C -I- -x aitio.ali
gnatlink aitio.ali -C --GCC=/usr/local/ada-build/friendly/gcc
xen:~/just_test OCTAGRAM$ ./aitio
 >>>8<<<
xen:~/just_test OCTAGRAM$ cat aitio.adb
with Ada.Text_IO;
with Ada.Integer_Text_IO;

use Ada;

procedure AITIO is

begin
    Text_IO.Put (">>>");
    Integer_Text_IO.Put (8, Width => 0);
    Text_IO.Put_Line ("<<<");
end AITIO;
xen:~/just_test OCTAGRAM$

But, once again, it looks stupid.

> Anyway, most of the time, the space is useful,

Integer'Image (-2) = "-2" -- no space here no matter how useful it is

-- 
If you want to get to the top, you have to start at the bottom



^ permalink raw reply	[relevance 6%]

* Re: How to print string, record variable while debugging with GDB using GPS
  2009-02-20 10:43  4%   ` Paruthi
@ 2009-02-20 13:21  0%     ` Paruthi
  0 siblings, 0 replies; 200+ results
From: Paruthi @ 2009-02-20 13:21 UTC (permalink / raw)


On Feb 20, 3:43 pm, Paruthi <sathishvelusw...@gmail.com> wrote:
> On Feb 19, 7:30 pm, Georg Bauhaus <rm.dash-bauh...@futureapps.de>
> wrote:
>
>
>
>
>
> > Paruthi schrieb:
>
> > > Hi,
>
> > > Can any one please help me how to print the value of the variable
> > > which is of a string type, instance of a record..etc while debugging
> > > with GDB using Ada code. For simple string I get the value in ascii
> > > value. Is there any way where I get the actual string value instead of
> > > ASCII value.
>
> > Did you use the GDB provided with your Ada environement?
>
> > (gdb) list
> > 1       procedure test is
> > 2               x: string(1..10);
> > 3       begin
> > 4               x := "ABCDEFGHIJ";
> > 5               x(1) := x(2);
> > 6       end;
> > (gdb) display x
> > 4: x = "["00"]["00"]["00"]["00"]["00"]["00"]["00"]["00"]&["1d"]"
> > (gdb) n
> > 5               x(1) := x(2);
> > 4: x = "ABCDEFGHIJ"
> > (gdb) n
> > 6       end;
> > 4: x = "BBCDEFGHIJ"
> > (gdb)
>
> Hello Georg,
>
> Thanks for the quick response and help. I tried your instruction it
> works well for the sample code. But I have a sample piece of code in
> that if i try to print the string value then the value is printed in
> ASCII. Please help me to print the value in actual string. The sample
> code is :
>
> package lib is
>   type T_Int is range -2**31 .. 2**31-1;
>   for T_Int'Size use 4 * 8;
>   type T_Char is new Character;
>   for T_Char'Size use 1 * 8;
>   subtype T_Pos is  T_Int range 1 .. T_Int'Last;
>   type T_string is array (T_Pos range <>) of T_Char;
>   function Get_Val(Status : in boolean) return t_string;
> end lib;
>
> with ada.text_io;
> with ada.integer_text_io;
> with lib;
> use lib;
> use ada.text_io;
> use ada.integer_text_io;
>
> procedure A is
>
>   type T_str (Size : T_Pos) is
>      record
>         tab : T_string(1..Size);
>         T_Nab : integer:=0;
>      end record;
>   type t_str_access is access all t_str;
>   A: T_string(1..10):= (' ',' ',' ',' ',' ',' ',' ',' ',' ',' ');
>   B:T_str(3);
>   c : integer;
>   status : boolean;
> begin
>   B.tab := "Var";
>   get(c);
>   if c = 1 then
>      status := false;
>   elsif c =2 then
>      status := true;
>   else
>      null;
>   end if;
>
>   c:= c+1;
>   put(c-1);
>   A := Get_Val(status);
> --     put(standard.string(A));
>
> end A ;
>
> With the above code try to print variable 'B.tab' this prints in
> ASCII. Please suggest some solution.
>
> Thanks in advance.
>
> Regards,
> Sathish V- Hide quoted text -
>
> - Show quoted text -

Along with the above I face one more problem. That is I get the below
error:

    gdb-internal-error: virtual memory exhausted: can't allocate 4072
bytes.
    1 [sig] gdb 15804 open_stackdumpfile: Dumping stack trace to
gdb.exe.stackdump

How to solve this problem? Please help me for this problem.

Thanks in advance.



^ permalink raw reply	[relevance 0%]

* Re: How to print string, record variable while debugging with GDB using GPS
  @ 2009-02-20 10:43  4%   ` Paruthi
  2009-02-20 13:21  0%     ` Paruthi
  0 siblings, 1 reply; 200+ results
From: Paruthi @ 2009-02-20 10:43 UTC (permalink / raw)


On Feb 19, 7:30 pm, Georg Bauhaus <rm.dash-bauh...@futureapps.de>
wrote:
> Paruthi schrieb:
>
> > Hi,
>
> > Can any one please help me how to print the value of the variable
> > which is of a string type, instance of a record..etc while debugging
> > with GDB using Ada code. For simple string I get the value in ascii
> > value. Is there any way where I get the actual string value instead of
> > ASCII value.
>
> Did you use the GDB provided with your Ada environement?
>
> (gdb) list
> 1       procedure test is
> 2               x: string(1..10);
> 3       begin
> 4               x := "ABCDEFGHIJ";
> 5               x(1) := x(2);
> 6       end;
> (gdb) display x
> 4: x = "["00"]["00"]["00"]["00"]["00"]["00"]["00"]["00"]&["1d"]"
> (gdb) n
> 5               x(1) := x(2);
> 4: x = "ABCDEFGHIJ"
> (gdb) n
> 6       end;
> 4: x = "BBCDEFGHIJ"
> (gdb)

Hello Georg,

Thanks for the quick response and help. I tried your instruction it
works well for the sample code. But I have a sample piece of code in
that if i try to print the string value then the value is printed in
ASCII. Please help me to print the value in actual string. The sample
code is :

package lib is
  type T_Int is range -2**31 .. 2**31-1;
  for T_Int'Size use 4 * 8;
  type T_Char is new Character;
  for T_Char'Size use 1 * 8;
  subtype T_Pos is  T_Int range 1 .. T_Int'Last;
  type T_string is array (T_Pos range <>) of T_Char;
  function Get_Val(Status : in boolean) return t_string;
end lib;

with ada.text_io;
with ada.integer_text_io;
with lib;
use lib;
use ada.text_io;
use ada.integer_text_io;

procedure A is

  type T_str (Size : T_Pos) is
     record
        tab : T_string(1..Size);
        T_Nab : integer:=0;
     end record;
  type t_str_access is access all t_str;
  A: T_string(1..10):= (' ',' ',' ',' ',' ',' ',' ',' ',' ',' ');
  B:T_str(3);
  c : integer;
  status : boolean;
begin
  B.tab := "Var";
  get(c);
  if c = 1 then
     status := false;
  elsif c =2 then
     status := true;
  else
     null;
  end if;

  c:= c+1;
  put(c-1);
  A := Get_Val(status);
--     put(standard.string(A));

end A ;

With the above code try to print variable 'B.tab' this prints in
ASCII. Please suggest some solution.

Thanks in advance.

Regards,
Sathish V



^ permalink raw reply	[relevance 4%]

* Re: Restarting Tread: Why isn't this program working with
       [not found]     <83d19cd8-71ca-43c1-a3eb-05832290e565@r36g2000prf.googlegroups.com>
@ 2009-01-16  1:37  6% ` anon
  0 siblings, 0 replies; 200+ results
From: anon @ 2009-01-16  1:37 UTC (permalink / raw)


--
--  Three different versions.  All version use 8-bits instead of 7-bits 
--  because integer version of 200.0 may not fit in a 7-bit code.
--  use declare blocks to separate versions.
--
with Ada.Integer_Text_IO ;
with Ada.Float_Text_IO ;

with Ada.Text_IO ;
use  Ada.Text_IO ;

with Ada.Unchecked_Conversion;

with Interfaces ;
use  Interfaces ;

procedure test2 is
  subtype Short_integer1 is INTEGER range -(2 ** 7)..((2 ** 7) - 1);
  subtype A_Float is Float;

  subtype Short_integer2 is Integer range 0.. ((2 ** 8) - 1);
  subtype A_Natural is Natural range 0..((2 ** 8) - 1);

  --FYI1
  Size_Of_Float : integer := Float'Size;                  -- 32
  Size_Of_short_int: integer := Short_integer1'Size;      -- 10 !!!!!!! Size is 10

  --FYI2
  Size_Of_short_integer: integer := Short_integer2'Size;  -- 8
  Size_Of_Natural: integer := A_Natural'Size;             -- 8

  Arg    : A_Float;
  Result : Short_integer1;


Begin

   -- will cause error due to integer version of 200 is 
   -- greater than 2**7

  begin
    Arg := 200.0;
    Result := Short_integer1(Arg);
  exception
    when Constraint_Error =>
      Put_Line ( "Constraint_Error using Short_integer1" ) ;
  end ;

  -- using files 

  declare
   Temp_String : String ( 1..10 ) ; 
   Temp : Integer ; 
   Last : Positive ;
   Result2 : Short_integer2;
 
  begin
    Arg := 200.0;
    Ada.Float_Text_IO.Put ( Temp_String, Arg, Aft => 0, Exp => 0 ) ;
    Ada.Integer_Text_IO.Get ( Temp_String, Temp, Last ) ;
    Result2 := Short_integer2(Temp);
    Put_Line ( "Temp :=> " & Temp_String ) ;
    Put ( "Result from file :=> " ) ;
    Ada.Integer_Text_IO.Put ( Result2 ) ;
    New_Line ;
  exception
    when Constraint_Error =>
      Put_Line ( "Constraint_Error using Files" ) ;
      Put_Line ( "Temp :=> " & Temp_String ) ;
  end ;



  -- Works but the number may be greater than 7 bits code.

  declare 
    function To_Integer is new Ada.Unchecked_Conversion 
                          ( Float, Integer ) ;
    Temp : Integer ; 
  begin
    Arg := 200.0;
    Temp := To_Integer ( Arg ) ;
    Put ( "Result :=> " ) ;
    Ada.Integer_Text_IO.Put ( Temp ) ;
    new_line ;
  exception
    when Constraint_Error =>
      Put_Line ( "Constraint_Error using Unchecked_Conversion" ) ;
  end ;


  -- Works but the number may be greater than 7 bits code, so using 8

  declare 
    type Irec is array ( 0..3 ) of Unsigned_8 ;
                       
    function To_Integer is new Ada.Unchecked_Conversion 
                          ( Float, Irec ) ;
    Temp : Irec ; 
  begin
    Arg := 200.0;
    Temp := To_Integer ( Arg ) ;
    Put ( "Result :=> " ) ;
      for index in IRec'range loop
        Ada.Integer_Text_IO.Put ( Integer ( Temp ( index ) ), 8, 16 );
      end loop ;
    new_line ;
  exception
    when Constraint_Error =>
      Put_Line ( "Constraint_Error using Unchecked_Conversion" ) ;
  end ;
End test2;



In <83d19cd8-71ca-43c1-a3eb-05832290e565@r36g2000prf.googlegroups.com>, ChristopherL <clusardi2k@aol.com> writes:
>I'm restarting the tread [How to put 200 into an integer sub-type of
>16 bits (code included)] with a new subject because the last was too
>long!
>
>How can I be getting the below error message with
>"Unchecked_Conversion".
>
>Isn't Unchecked_conversion just suppose to copy bits?
>
>I want to copy bits from an Ada float to a user defined short integer
>maintaining the same bit representation.
>
>Arg:Float;  -- From this with a value of 200
>subtype Short_integer is Integer range -(2 ** 7) .. ((2 ** 7) - 1 );
>Result: Short_integer; --to this, and I want to round Arg
>
>The definitions of Arg and Result2 can not chanage.
>
>Chris L.
>
>with Unchecked_Conversion;
>
>procedure test is
>  subtype Short_integer1 is Natural range 0.. ((2 ** 10) - 1);
>  subtype Short_integer2 is Integer range -(2 ** 7)..((2 ** 7) - 1);
>
>  subtype A_Float is Float;
>
>  subtype A_Natural is Natural range 0..((2 ** 8) - 1);
>  -- The next line of code (if used) gives compilation error message:
>  -- A_NATURAL does not denote a first subtype
>  -- for A_Natural'Size use Short_integer1'Size;
>
>  Size_Of_Float : integer :=3D Float'Size;      --32 bits long
>
>  Size_Of_short_integer: integer :=3D Short_integer1'Size;--10 bits
>long
>  Size_Of_short_int: integer :=3D Short_integer2'Size;--10 bits long
>
>  Size_Of_Natural: integer :=3D A_Natural'Size;       --8 bits long
>
>  Arg     : A_Float;
>  Result2 : Short_integer2;
>  Result1 : Short_integer1;
>
>  function Get_Bits is new Unchecked_Conversion (Source =3D>
>    Short_integer1, Target =3D> Short_integer2);
>
>Begin
>
>Arg :=3D 200.0;
>
>Result1 :=3D Short_integer1(Arg + 0.5);  -- Result1 becomes 201
>Result2 :=3D Get_Bits (Result1);
>
>End test;
>
>-- Error Message
>+++ Program  started at 01/15/09 12:14:02
>
>Unhandled exception:
>
>CONSTRAINT_ERROR raised in MAIN
>
>Range_Check_Failed
>
>Exception raised at code address: 0x413516
>+++ Program completed with exit code 1 at 01/15/09 12:14:02
>+++
>---------------------------------------------------------------------------=
>=AD-----------------------------------




^ permalink raw reply	[relevance 6%]

* Re: GNAT: Weird Style Warnings
  2008-10-26 12:17  5% GNAT: Weird Style Warnings jacob.m.h.smith
@ 2008-10-26 15:22  0% ` anon
  0 siblings, 0 replies; 200+ results
From: anon @ 2008-10-26 15:22 UTC (permalink / raw)


GNAT uses an Indentation value of 3, so when you reassign the indentation to 2 
some system files may report this error when scanned.

The best solution is to either use indentation of 3 in your program or skip 
the indentation style check.


In <6078a089-927b-4756-81a8-7c344df1ee16@u65g2000hsc.googlegroups.com>, jacob.m.h.smith@googlemail.com writes:
>Hello.
>
>I am pretty new to Ada and I have a problem I'm not able to solve.
>I compile my files with the following GNAT style switch: -
>gnaty2acefhiklmM78nprt
>When compiling this one adb file I always get the following message:
>s-expuns.ads:42:04: (style) bad indentation
>s-expuns.ads:44:04: (style) bad indentation
>I have no idea why. This file "s-expuns.ads" is not one of mine, it
>must be part of
>some library. Does anyone know the meaning of this?
>
>Here's the program text (It's no important project, I was just
>experimenting):
>
>-----------------------------------------------------------------------------
>with Ada.Integer_Text_IO, Interfaces;
>use  Ada.Integer_Text_IO, Interfaces;
>
>procedure Bit_Extraction is
>
>  subtype Byte is Unsigned_8;
>
>  function Get_Bits (The_Byte, Mask : Byte) return Byte is
>    Position : Natural := 0;
>  begin
>    while ((2**Position and Mask) = 0) loop
>      Position := Position + 1;
>    end loop;
>    return Shift_Right ((The_Byte and Mask), Position);
>  end Get_Bits;
>
>  Test_Byte, Test_Result : Byte;
>
>begin
>
>  --  Test_Byte: 247 => 11110111
>  Test_Byte := 247;
>
>  --  Test_Result: 7 => 111
>  Test_Result := Get_Bits (Test_Byte, 224);
>
>  Put (Integer (Test_Result), 0);
>
>end Bit_Extraction;
>-----------------------------------------------------------------------------
>
>Greetings,
>Jacob M. H. Smith




^ permalink raw reply	[relevance 0%]

* GNAT: Weird Style Warnings
@ 2008-10-26 12:17  5% jacob.m.h.smith
  2008-10-26 15:22  0% ` anon
  0 siblings, 1 reply; 200+ results
From: jacob.m.h.smith @ 2008-10-26 12:17 UTC (permalink / raw)


Hello.

I am pretty new to Ada and I have a problem I'm not able to solve.
I compile my files with the following GNAT style switch: -
gnaty2acefhiklmM78nprt
When compiling this one adb file I always get the following message:
s-expuns.ads:42:04: (style) bad indentation
s-expuns.ads:44:04: (style) bad indentation
I have no idea why. This file "s-expuns.ads" is not one of mine, it
must be part of
some library. Does anyone know the meaning of this?

Here's the program text (It's no important project, I was just
experimenting):

-----------------------------------------------------------------------------
with Ada.Integer_Text_IO, Interfaces;
use  Ada.Integer_Text_IO, Interfaces;

procedure Bit_Extraction is

  subtype Byte is Unsigned_8;

  function Get_Bits (The_Byte, Mask : Byte) return Byte is
    Position : Natural := 0;
  begin
    while ((2**Position and Mask) = 0) loop
      Position := Position + 1;
    end loop;
    return Shift_Right ((The_Byte and Mask), Position);
  end Get_Bits;

  Test_Byte, Test_Result : Byte;

begin

  --  Test_Byte: 247 => 11110111
  Test_Byte := 247;

  --  Test_Result: 7 => 111
  Test_Result := Get_Bits (Test_Byte, 224);

  Put (Integer (Test_Result), 0);

end Bit_Extraction;
-----------------------------------------------------------------------------

Greetings,
Jacob M. H. Smith



^ permalink raw reply	[relevance 5%]

* Re: determining input data type
    2008-10-18  6:53  5% ` deadlyhead
@ 2008-10-18 18:54  4% ` anon
  1 sibling, 0 replies; 200+ results
From: anon @ 2008-10-18 18:54 UTC (permalink / raw)


--
-- Without knowing what format your data is in it is kind of 
-- hard to decide what way is the best. Some ways are easy 
-- while others are more complex
--
-- But if the data is a packed buffer string then you could use 
-- Ada.Characters.Handling.Is_Digit.
--
-- In this case the best was is to use a loop and search for all 
-- valid data where the search routine would find the integer 
-- value and no error occurs unless the data is float. Also in this 
-- example, only base 10 integers are valid.
--
with Ada.Text_IO ;
use Ada.Text_IO ;

with Ada.Integer_Text_IO ;
use Ada.Integer_Text_IO ;

with Ada.Characters.Handling ;
use  Ada.Characters.Handling ;

procedure b is

  Data_Error : exception ;

  function To_Integer ( Buffer : String ) return Integer is

    Index : Natural ;
    First : Natural ; -- first valid digit
    Last  : Natural ; -- Last valid digit

  begin -- To_Integer
    Index := Buffer'First ;
    while Index <= Buffer'Last and then 
          not is_digit ( Buffer ( Index ) ) loop 
      Index := Index + 1 ;
    end loop ;
    First := Index ; 

    while Index <= Buffer'Last and then
          is_digit ( Buffer ( Index ) ) loop 
      Index := Index + 1 ;
    end loop ;
    Last := Index - 1 ;

    --  check for decimal point aka the number is float

    if Index <= Buffer'Last and then
       Buffer ( Index ) = '.' then  
       raise Data_Error ;
    end if ;
  
    return Integer'Value ( Buffer ( First..Last ) ) ;

  exception
    when Data_Error =>
      Put_Line ( "Data was invalid -- need to check data source" ) ;
      Put_Line ( "Invalid Data element =>" & Buffer ( Index ) ) ;
      raise ;
  end To_Integer ;


  Data   : integer ;

begin -- b

  Data := To_Integer ( " =123;" ) ;

  Put ( "Data => " ) ;
  Put ( Data ) ;
  New_Line ;


  -- Data_Error is raised

  Data := To_Integer ( "asv456" ) ; 

  Put ( "Data => " ) ;
  Put ( Data ) ;
  New_Line ;

  -- Data_Error is raised

  Data := To_Integer ( " =789.;" ) ; 

  Put ( "Data => " ) ;
  Put ( Data ) ;
  New_Line ;

exception
  when Data_Error =>
      null ;
end b ;

In <d39e1918-0c74-40b5-860d-f8d93181afd2@p59g2000hsd.googlegroups.com>, jedivaughn <jedivaughn14@gmail.com> writes:
>Hi, How is the best way to determine the type of input. I have the
>input coming in through a string but if the contents of the string is
>an integer then I want to convert it to such. This seems like it
>should be very easy to do but I can't seem to find out how to do it
>any where.
>
>
>Thanks,
>
>John




^ permalink raw reply	[relevance 4%]

* Re: determining input data type
  2008-10-18  6:53  5% ` deadlyhead
@ 2008-10-18  8:00  0%   ` Dmitry A. Kazakov
  0 siblings, 0 replies; 200+ results
From: Dmitry A. Kazakov @ 2008-10-18  8:00 UTC (permalink / raw)


On Fri, 17 Oct 2008 23:53:54 -0700 (PDT), deadlyhead wrote:

> Using Ada.Integer_Text_IO.Get does some work for you, though.  For
> instance, if the user inputs 214yy0, it puts 214 in My_Int and
> continues on its way.  This may not be what you want, thus some actual
> text processing may be in order.

Yes, this was one of the motivations behind:

   http://www.dmitry-kazakov.de/ada/strings_edit.htm 

Your example reworked for Strings_Edit:

with Ada.Text_IO;            use Ada.Text_IO;
with Strings_Edit.Integers;  use Strings_Edit.Integers;

procedure Int_Test is
   My_Int : Integer;
begin
   Put ("Give me some input, and I will tell you if it is an integer:");
   My_Int := Value (Get_Line);
   Put_Line (Image (My_Int) & " is an integer!");
exception
   when Constraint_Error =>
      Put_Line ("That was a too large integer!");
   when End_Error =>
      Put_Line ("You entered nothing!");
   when Data_Error =>
      Put_Line ("That was not an integer!");
end Int_Test;

The function Value takes care to check the whole string for containing
integer and nothing but integer.

-- 
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de



^ permalink raw reply	[relevance 0%]

* Re: determining input data type
  @ 2008-10-18  6:53  5% ` deadlyhead
  2008-10-18  8:00  0%   ` Dmitry A. Kazakov
  2008-10-18 18:54  4% ` anon
  1 sibling, 1 reply; 200+ results
From: deadlyhead @ 2008-10-18  6:53 UTC (permalink / raw)


On Oct 17, 5:48 pm, jedivaughn <jedivaugh...@gmail.com> wrote:
> Hi, How is the best way to determine the type of input. I have the
> input coming in through a string but if the contents of the string is
> an integer then I want to convert it to such. This seems like it
> should be very easy to do but I can't seem to find out how to do it
> any where.
>
> Thanks,
>
> John

Exceptions are a wonderful thing:

--  file: int_test.adb
--  Tests to see if an input string is an integer

with Ada.Text_IO;   use Ada.Text_IO;
with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;

procedure Int_Test is

   My_Int : Integer;

begin

   Put("Give me some input, and I will tell you if it is an integer:
");
   Get(My_Int);

   Put(My_Int, 0);
   Put(" is an integer!");
   New_Line;

exception
   when Data_Error =>
      Put("That was not an integer!");
      New_Line;
end Int_Test;

Using Ada.Integer_Text_IO.Get does some work for you, though.  For
instance, if the user inputs 214yy0, it puts 214 in My_Int and
continues on its way.  This may not be what you want, thus some actual
text processing may be in order.

-- deadlyhead



^ permalink raw reply	[relevance 5%]

* Re: Using a string as a binary operator
  2008-10-14 15:35  5% Using a string as a binary operator Joe
                   ` (2 preceding siblings ...)
  2008-10-15  3:51  0% ` Gene
@ 2008-10-15  5:45  0% ` anon
  3 siblings, 0 replies; 200+ results
From: anon @ 2008-10-15  5:45 UTC (permalink / raw)


First, it seams that your talking about a version of "Polish notation" or 
"Lisp notation".  There are 100s of articles and some sample program 
across the net.  Just do a search, and these article should give more 
information than you have question for.

For a starter in this simple example there will be one push/pop function 
one for "operations" and the other for numeric values.


  type operations is ( add, sub, mul, div, equal ) ;  - sample list
  for operations use ( noop => 0, add => 1,  sub   => 2,
                        mul  => 3, div => 4,  equal => 5 ) ;  - sample list


  procedure do_notation ( buffer : string ) is  

      operation_code : character ;

    begin

      -- decode operation_code and arguments from buffer 

       -- push arguments 

       push ( arg1 )  ;  -- push numeric value of argument 1 and 2
       push ( arg2 )  ;

      case operation_code is
        when '+' =>
            push ( add )  ;
        when '-' =>
            push ( sub ) ;
        ...
        when others =>
            raise Operations_Error ; - illegal operation
        end case ;
    end ;

-----

  function process_notation return data_type is
    cmd : operations ;  
    begin 
      arg1 := pop ;
      arg2 := pop ;
      cmd := pop ;
      case cmd is 
        when add =>
          result := arg1 + arg2 ;
        when sub =>
          result := arg1 - arg2 ;
        when div =>
          if arg2 /= 0 then
            result := arg1 / arg2 ;
          else
            raise Div_Zero_Error ;
          end ;
       ...
        when others =>
          raise Stack_Error ;
      end case ;

      -- Display or return result.

    end ;


    result : data_type ; -- data_type is user assigned numeric type

begin
   push ( noop )  ; -- not needed. Used only for showing stack list
   -- stack should have ( 0, ... )

   do_notation ( "5 + 10" ) ; 
   -- stack should have ( 5, 10, 1, 0, ... )

   result := process_notation ; 
  -- If the  then after  the stack should have ( 0, ... ) and result := 15

  ...
end ;


In <8cbb04c3-e789-4b67-897a-fd6f83486bbc@x16g2000prn.googlegroups.com>, Joe <joesmoe10@gmail.com> writes:
>Hey all,
>
>I'm trying to build a simple stack the evaluates expressions in
>postfix notation (i.e. "1 2 +").  I can't find a way to use the
>operator directly when I get to it.  When I get to the  "+", but how
>do I apply this string to 1 and 2?  The best I can do is make a case
>statement that has a case for each binary operator, but this seems
>very klunky.  I know you can write "+"(1,2) to return 3 but how do I
>get Ada to recognize the string as an operator?  Here's a short
>example of what I would like to do:
>
>with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;
>procedure Operators is
>   Plus : String := "+";
>begin
>   Put( Plus(1,2));
>end Operators;
>
>Thanks,
>Joe




^ permalink raw reply	[relevance 0%]

* Re: Using a string as a binary operator
  2008-10-14 15:35  5% Using a string as a binary operator Joe
  2008-10-14 17:05  5% ` Dmitry A. Kazakov
  2008-10-14 22:01  0% ` george.priv
@ 2008-10-15  3:51  0% ` Gene
  2008-10-15  5:45  0% ` anon
  3 siblings, 0 replies; 200+ results
From: Gene @ 2008-10-15  3:51 UTC (permalink / raw)


On Oct 14, 11:35 am, Joe <joesmo...@gmail.com> wrote:
> Hey all,
>
> I'm trying to build a simple stack the evaluates expressions in
> postfix notation (i.e. "1 2 +").  I can't find a way to use the
> operator directly when I get to it.  When I get to the  "+", but how
> do I apply this string to 1 and 2?  The best I can do is make a case
> statement that has a case for each binary operator, but this seems
> very klunky.  I know you can write "+"(1,2) to return 3 but how do I
> get Ada to recognize the string as an operator?  Here's a short
> example of what I would like to do:
>
> with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;
> procedure Operators is
>    Plus : String := "+";
> begin
>    Put( Plus(1,2));
> end Operators;
>

The "+" in Ada code such as "+"(1, 2) is a function call, just like
f(1, 2).  You can't cast a string "+" to a function in Ada, just as
you can't cast "f".  You have to convert the string yourself.  Here is
a toy code with many things go fix:

with Ada.Text_IO; use Ada.Text_IO;

procedure Postfix is

   subtype Number is Integer;

   Operands : array(1 .. 1000) of Number;
   SP : Natural := 0;

   procedure Push(X : in Number) is
   begin
      SP := SP + 1;
      Operands(SP) := X;
   end Push;

   procedure Pop(X : out Number) is
   begin
      X := Operands(SP);
      SP := SP - 1;
   end Pop;

   Buf : String(1 .. 1000);
   Last : Natural;
   X, Y : Number;
begin
   loop
      Get_Line(Buf, Last);
      exit when Last = 0;
      case Buf(1) is
         when '+' =>
            Pop(X); Pop(Y); Push(X + Y);
         when '-' =>
            Pop(X); Pop(Y); Push(X - Y);
         when '*' =>
            Pop(X); Pop(Y); Push(X * Y);
         when '/' =>
            Pop(X); Pop(Y); Push(X / Y);
         when others =>
            Push(Number'Value(Buf(1 .. Last)));
      end case;
      if SP = 1 then
         Put_Line(Number'Image(Operands(1)));
      end if;
   end loop;
end Postfix;



^ permalink raw reply	[relevance 0%]

* Re: Using a string as a binary operator
  2008-10-14 15:35  5% Using a string as a binary operator Joe
  2008-10-14 17:05  5% ` Dmitry A. Kazakov
@ 2008-10-14 22:01  0% ` george.priv
  2008-10-15  3:51  0% ` Gene
  2008-10-15  5:45  0% ` anon
  3 siblings, 0 replies; 200+ results
From: george.priv @ 2008-10-14 22:01 UTC (permalink / raw)


On Oct 14, 11:35 am, Joe <joesmo...@gmail.com> wrote:
> Hey all,
>
> I'm trying to build a simple stack the evaluates expressions in
> postfix notation (i.e. "1 2 +").  I can't find a way to use the
> operator directly when I get to it.  When I get to the  "+", but how
> do I apply this string to 1 and 2?  The best I can do is make a case
> statement that has a case for each binary operator, but this seems
> very klunky.  I know you can write "+"(1,2) to return 3 but how do I
> get Ada to recognize the string as an operator?  Here's a short
> example of what I would like to do:
>
> with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;
> procedure Operators is
>    Plus : String := "+";
> begin
>    Put( Plus(1,2));
> end Operators;
>
> Thanks,
> Joe

You are confusing compile time and run time phases of your program's
life.  When you call "+"(a,b), it is treated as any other function
(Could have been Add(a,b)). Ada overload feature allows for more
convenient substitution in form a+b.  The construct is recognized
during compilation of the source code.   At run time compiler is no
longer used and sometimes unavailable.  So you have to write your own
parser that will handle your input string.  There is plentiful code
samples out there on the WEB in variety of languages I am sure.

George.




^ permalink raw reply	[relevance 0%]

* Re: Using a string as a binary operator
  2008-10-14 15:35  5% Using a string as a binary operator Joe
@ 2008-10-14 17:05  5% ` Dmitry A. Kazakov
  2008-10-14 22:01  0% ` george.priv
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 200+ results
From: Dmitry A. Kazakov @ 2008-10-14 17:05 UTC (permalink / raw)


On Tue, 14 Oct 2008 08:35:23 -0700 (PDT), Joe wrote:

> I'm trying to build a simple stack the evaluates expressions in
> postfix notation (i.e. "1 2 +").  I can't find a way to use the
> operator directly when I get to it.  When I get to the  "+", but how
> do I apply this string to 1 and 2?  The best I can do is make a case
> statement that has a case for each binary operator, but this seems
> very klunky.  I know you can write "+"(1,2) to return 3 but how do I
> get Ada to recognize the string as an operator?  Here's a short
> example of what I would like to do:
> 
> with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;
> procedure Operators is
>    Plus : String := "+";
> begin
>    Put( Plus(1,2));
> end Operators;

with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;
procedure Operators is
   function Plus (L, R : Integer) return Integer renames "+";
begin
   Put (Plus (1, 2));
end Operators;

P.S. I am quite sure that this is not what you need. You don't need strings
in order to evaluate an expression. Evaluation of an expression /= parsing
an expression. It is unclear which one you actually want, or maybe both.

P.P.S. Ada does not "recognize strings as operators." "+" when used to
declare or reference + is technically not a string. It is a string literal.

-- 
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de



^ permalink raw reply	[relevance 5%]

* Using a string as a binary operator
@ 2008-10-14 15:35  5% Joe
  2008-10-14 17:05  5% ` Dmitry A. Kazakov
                   ` (3 more replies)
  0 siblings, 4 replies; 200+ results
From: Joe @ 2008-10-14 15:35 UTC (permalink / raw)


Hey all,

I'm trying to build a simple stack the evaluates expressions in
postfix notation (i.e. "1 2 +").  I can't find a way to use the
operator directly when I get to it.  When I get to the  "+", but how
do I apply this string to 1 and 2?  The best I can do is make a case
statement that has a case for each binary operator, but this seems
very klunky.  I know you can write "+"(1,2) to return 3 but how do I
get Ada to recognize the string as an operator?  Here's a short
example of what I would like to do:

with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;
procedure Operators is
   Plus : String := "+";
begin
   Put( Plus(1,2));
end Operators;

Thanks,
Joe



^ permalink raw reply	[relevance 5%]

Results 1-200 of ~610   | reverse | options above
-- pct% links below jump to the message on this page, permalinks otherwise --
2008-10-14 15:35  5% Using a string as a binary operator Joe
2008-10-14 17:05  5% ` Dmitry A. Kazakov
2008-10-14 22:01  0% ` george.priv
2008-10-15  3:51  0% ` Gene
2008-10-15  5:45  0% ` anon
2008-10-18  0:48     determining input data type jedivaughn
2008-10-18  6:53  5% ` deadlyhead
2008-10-18  8:00  0%   ` Dmitry A. Kazakov
2008-10-18 18:54  4% ` anon
2008-10-26 12:17  5% GNAT: Weird Style Warnings jacob.m.h.smith
2008-10-26 15:22  0% ` anon
     [not found]     <83d19cd8-71ca-43c1-a3eb-05832290e565@r36g2000prf.googlegroups.com>
2009-01-16  1:37  6% ` Restarting Tread: Why isn't this program working with anon
2009-02-19 11:56     How to print string, record variable while debugging with GDB using GPS Paruthi
2009-02-19 14:30     ` Georg Bauhaus
2009-02-20 10:43  4%   ` Paruthi
2009-02-20 13:21  0%     ` Paruthi
2009-02-24 11:03     Invade wikipedia! Jean-Pierre Rosen
2009-02-25 22:31     ` Ivan Levashew
2009-02-26 10:40       ` Jean-Pierre Rosen
2009-02-26 13:53  6%     ` Ivan Levashew
2009-04-28 17:04     Problem with optimizations Olivier Scalbert
2009-04-28 18:40  3% ` (see below)
2009-04-28 19:05  0%   ` Albrecht Käfer
2009-04-28 19:15  0%     ` Olivier Scalbert
2009-04-29 10:36  0%       ` johnscpg
2009-04-29 10:45  0%       ` johnscpg
2009-04-29 13:51  0%       ` johnscpg
2009-04-28 19:06  0%   ` Olivier Scalbert
2009-04-28 19:12  0%     ` (see below)
2009-04-29  2:35  0%       ` Gene
2009-05-08 20:50     How it works get_line function juanmiuk
2009-05-08 21:33     ` Jeffrey R. Carter
2009-05-09 20:56  5%   ` juanmiuk
2009-06-01  7:57     BASIC_NUM_IO Georg
2009-06-01  8:18  6% ` BASIC_NUM_IO anon
2009-06-28 17:56     unsigned type anon
2009-06-28 19:54     ` tmoran
2009-06-29 13:36       ` Rob Solomon
2009-06-29 15:37  3%     ` Adam Beneschan
2009-06-28 23:08     anon
2009-07-01  1:39     ` Adam Beneschan
2009-07-02 19:49  4%   ` anon
2009-07-03  1:42  0%     ` anon
2009-07-09 23:10  4% getting back to null range anon
2009-07-12 18:20  4% ` AdaMagica
2009-07-14 22:46  5% float confusion Rob Solomon
2009-07-14 23:26  0% ` Randy Brukardt
2009-07-14 23:50  0% ` Adam Beneschan
2009-07-15  0:03  0%   ` Rob Solomon
2009-07-15  0:18  0%     ` Adam Beneschan
2009-07-21 11:42  4% Can a child access private types of its parent? vlc
2009-07-21 12:05  5% ` Dmitry A. Kazakov
2009-07-21 12:07  5% ` Martin
2009-08-05 10:40  2% Gnatbench 2.3.1 doing funny thing - any ideas? John McCabe
2010-04-27 19:34  4% Min/Max attribute makes promises it can't keep Alex Mentis
2010-04-27 20:20  0% ` Martin
2010-04-27 21:16       ` Robert A Duff
2010-04-28 10:36  5%     ` Alex Mentis
2010-09-11  4:24     Inefficient algorithms Rick
2010-09-15  1:11  5% ` BrianG
2010-09-26  8:14  4% loop problem with exit condition Ada novice
2010-10-31 22:00  5% Beginners question: Compound types, how-to? Mart van de Wege
2010-11-01  3:55  0% ` Jeffrey Carter
2010-11-01  7:12  0%   ` Mart van de Wege
2010-11-27  9:47     Callback in Ada Georg Maubach
2010-11-27 10:26  5% ` Alex Mentis
2010-12-23 15:37  5% Problems with network printer tchaco
2010-12-27 18:26  5% An Example for Ada.Execution_Time anon
2010-12-30 10:43  5% Random number generation Mart van de Wege
2010-12-30 11:34  0% ` Niklas Holsti
2010-12-30 11:51  0% ` Brian Drummond
2010-12-30 13:04  4% ` Dmitry A. Kazakov
2011-02-18 22:52     Need some light on using Ada or not Luis P. Mendes
2011-02-19 13:07     ` Brian Drummond
2011-02-19 14:36       ` Georg Bauhaus
2011-02-19 18:25         ` Brian Drummond
2011-02-20 14:34  4%       ` Brian Drummond
2011-02-20 15:45             ` jonathan
2011-02-20 19:49               ` Pascal Obry
2011-02-20 19:57                 ` Brian Drummond
2011-02-20 22:47                   ` Simon Wright
2011-02-21 12:52  3%                 ` Brian Drummond
2011-02-21 13:44  3%                   ` Simon Wright
2011-02-22  2:15  1%                   ` Shark8
2011-02-20  0:20       ` Luis P. Mendes
2011-02-20 19:54  4%     ` Brian Drummond
2011-02-23 22:19  0%       ` Luis P. Mendes
2011-03-09 18:55     Anyone see a problem in 5.7 ncurses Ada? localhost
2011-03-09 20:28  4% ` Emile8
2011-03-31 23:40     ada question Robin
2011-04-01  1:33  5% ` Nasser M. Abbasi
2011-04-01 10:53     index check failure - constraint error tonyg
2011-04-01 11:07     ` tonyg
2011-04-01 11:27  6%   ` Alex Mentis
2011-04-20 10:39     If not Ada, what else Alex R. Mosteo
2015-07-21 17:29     ` Niklas Holsti
2015-07-21 18:51       ` Simon Wright
2015-07-21 19:36         ` David Botton
2015-07-22 12:00           ` Jean François Martinez
2015-07-27 22:59             ` Randy Brukardt
2015-07-29 12:38               ` EGarrulo
2015-07-29 15:41                 ` Paul Rubin
2015-07-29 17:07                   ` Stefan.Lucks
2015-07-29 17:47                     ` Paul Rubin
2015-08-21 23:03                       ` Waldek Hebisch
2015-08-22  3:24                         ` Paul Rubin
2015-08-23 16:26  5%                       ` Waldek Hebisch
2015-08-23 17:18  0%                         ` Jeffrey R. Carter
2015-08-23 17:31  0%                           ` Waldek Hebisch
2011-05-25 14:54  3% Interesting and possible buggy behavior in GNAT regarding Annex E pragmas Shark8
2011-06-14 21:12     I need feedback juanmiuk
2011-06-14 21:50     ` Ludovic Brenta
2011-06-15 11:40       ` Yannick Duchêne (Hibou57)
2011-06-15 19:38         ` Shark8
2011-06-16  4:24  5%       ` juanmiuk
2011-06-16  7:34  0%         ` Ludovic Brenta
2011-06-15  6:01     My first solution juanmiuk
2011-06-15  6:39  4% ` Ludovic Brenta
2012-02-09  1:03     Need Help On Ada95 Problem Will
2012-02-09  2:01     ` Shark8
2012-02-10  1:36       ` BrianG
2012-02-10  2:22         ` Shark8
2012-02-10  5:32  5%       ` Alex
2012-02-10 15:19             ` Shark8
2012-02-10 20:07               ` Robert A Duff
2012-02-12 19:40  5%             ` Will
2012-03-06 21:19     Ada and linux real time slos
2012-03-07  8:23     ` Dmitry A. Kazakov
2012-03-07 12:10       ` slos
2012-03-07 14:18         ` Dmitry A. Kazakov
2012-03-08  2:38           ` Eilie
2012-03-08 12:04             ` Simon Clubley
2012-03-08 21:45               ` slos
2012-03-15  2:35                 ` BrianG
2012-03-16 20:36                   ` slos
2012-03-17 12:34                     ` Simon Wright
2012-03-17 15:50  4%                   ` Simon Wright
2012-04-06 15:20     In case you need to remember mockturtle
2012-04-06 20:09  4% ` anon
2012-06-26 13:47  5% how to print an array range? Nasser M. Abbasi
2012-06-26 13:54     ` Georg Bauhaus
2012-06-26 14:08  5%   ` Nasser M. Abbasi
2012-06-26 14:24  5%     ` Nasser M. Abbasi
2012-06-26 15:53           ` Georg Bauhaus
2012-06-26 16:28             ` Nasser M. Abbasi
2012-06-26 17:05               ` John B. Matthews
2012-06-26 17:13                 ` Georg Bauhaus
2012-06-26 19:28  5%               ` John B. Matthews
2012-06-28  6:59  0% ` Shark8
2012-07-04  7:48  4% “Parallel Sort” Program in Essence Austin Obyrne
2012-08-12  1:14  5% can Ada give run-time error or warning for integer division with non-zero remainder? Nasser M. Abbasi
2012-08-12  6:45  0% ` Dmitry A. Kazakov
2012-08-12  7:16  0% ` Per Sandberg
2012-08-12 14:19  0% ` Robin Vowels
2012-10-05 22:23     How to get generic formal parameter type into base class kevin.miscellaneous
2012-10-06  3:28     ` Adam Beneschan
2012-10-06 20:03       ` kevin andrew
2012-10-07  3:06         ` Adam Beneschan
2012-10-11 20:25           ` kevin andrew
2012-10-11 23:52  4%         ` Georg Bauhaus
2013-05-23 13:53  5% Simple loop with a strange output Luca Cappelletti
2013-05-23 13:55  0% ` Luca Cappelletti
2013-06-16  6:54  5% Beginner issue Marcus F
2013-06-16  7:00  0% ` Marcus F
2013-12-07 12:24     Will Ada-95 Programs Written in MS Windows Run in MacOS and Linux Without Some Tweaking Austin Obyrne
2013-12-07 13:16     ` Simon Wright
2013-12-07 14:01       ` Austin Obyrne
2013-12-07 17:18         ` Simon Wright
2013-12-07 18:26  4%       ` Austin Obyrne
2013-12-08 17:17             ` Simon Wright
2013-12-10  6:37               ` Randy Brukardt
2013-12-10 11:39  4%             ` Austin Obyrne
2013-12-10 21:49  0%               ` Randy Brukardt
2013-12-11 10:35  3%                 ` Austin Obyrne
2013-12-11  0:34  5%             ` Simon Wright
2014-01-28  1:06  3% need help learning Ada for a modula-2 programmer agent
2014-02-13 23:57  3% Something I don't understand Laurent
2014-02-14  0:18  0% ` adambeneschan
2014-02-14  7:05  0%   ` Charles H. Sampson
2014-02-15 15:27       ` Laurent
2014-02-15 19:10  4%     ` Laurent
2014-02-15 20:05  0%       ` Niklas Holsti
2014-02-16  1:39  0%       ` Robert A Duff
2014-03-04  9:46     Reading data from file Laurent
2014-03-04 18:08     ` Mike H
2014-03-04 21:27  4%   ` Laurent
2014-03-04 21:42  0%     ` Niklas Holsti
2014-03-05 13:59         ` Mike H
2014-03-05 20:33           ` Laurent
2014-03-05 21:00             ` Jeffrey Carter
2014-03-05 21:13  5%           ` Laurent
2014-03-05 21:25  0%             ` Niklas Holsti
2014-04-04  0:35  5% gnatmake error I don't understand agent
2014-04-04  4:14  0% ` Per Sandberg
2014-04-15 18:26     Problem with generic package Laurent
2014-04-15 20:41     ` Simon Wright
2014-04-15 21:12  4%   ` Laurent
2014-04-19 14:31     OpenSSL development (Heartbleed) Alan Browne
2014-04-19 15:36     ` Georg Bauhaus
2014-04-19 16:00       ` Yannick Duchêne (Hibou57)
2014-04-19 16:34         ` Georg Bauhaus
2014-04-21 23:51           ` Randy Brukardt
2014-04-22 15:20             ` G.B.
2014-04-22 16:33               ` Dmitry A. Kazakov
2014-04-22 16:57                 ` Simon Clubley
2014-04-22 19:53                   ` Dmitry A. Kazakov
2014-04-23  5:38                     ` Natasha Kerensikova
2014-04-23  7:30                       ` Dmitry A. Kazakov
2014-04-23  8:06  5%                     ` Georg Bauhaus
2014-05-14 19:06  6% Bug or feature? Laurent
2014-05-14 19:57     ` Adam Beneschan
2014-05-14 20:15  5%   ` Adam Beneschan
2014-06-09 12:15  4% Technical Question Austin Obyrne
2014-06-09 12:50  0% ` Austin Obyrne
2014-06-09 17:54  5%   ` Austin Obyrne
2014-07-19 21:37  5% Problem with output using Ada.Text_IO.Put junior learning ADA
2014-07-19 22:10  6% ` Jerry
2014-07-19 23:58  0% ` Jeffrey Carter
2014-07-20  5:22  0% ` Niklas Holsti
2014-09-07 12:29  5% Concurrency in Ada Stribor40
2014-10-07  5:23     permutation of strings Stribor40
2014-10-07  5:38     ` mockturtle
2014-10-07 11:22  5%   ` Brian Drummond
2014-10-14  1:17  5% passing messages between the tasks compguy45
2014-10-14  1:49  0% ` Adam Beneschan
2014-10-16 12:55  4% Gnat Pro Cross compiling Nahro Nadir
2014-10-24 16:44     confusion about message passing between the tasks compguy45
2014-10-25 17:25     ` Dennis Lee Bieber
2014-10-25 17:54       ` Jeffrey Carter
2014-10-25 22:23         ` Robert A Duff
2014-10-25 23:26  4%       ` compguy45
2014-10-27 12:09  4% Question about reference types rkodinets
2014-10-27 18:09  0% ` Martyn Pike
2014-11-29 13:28  3% Help with an errant 'IF' statement please Austin Obyrne
2014-11-29 14:03     ` gautier_niouzes
2014-11-29 15:05  4%   ` Austin Obyrne
2014-11-29 16:54         ` Dennis Lee Bieber
2014-11-30  2:16           ` Austin Obyrne
2014-11-30 11:18             ` Simon Clubley
2014-11-30 12:58  7%           ` Austin Obyrne
2014-11-30 13:01  0%             ` Austin Obyrne
2014-12-01 22:20  6%               ` Stephen Leake
2014-12-02  2:57  0%                 ` Austin Obyrne
2014-12-02 11:57     The enormous potential that programming LaTeX in Ada presents Austin Obyrne
2014-12-03 16:12     ` gautier_niouzes
2014-12-03 20:48       ` Austin Obyrne
2014-12-03 20:57         ` Pascal Obry
2014-12-03 22:39  4%       ` mrvmurray
2014-12-17 23:43     Ada Connections to this Crypto Simon Clubley
2014-12-18  1:07     ` Denis McMahon
2014-12-18  7:37       ` Austin Obyrne
2014-12-18 23:25         ` Denis McMahon
2014-12-19  8:09           ` Austin Obyrne
2014-12-19  8:24             ` MM
2014-12-19  9:02               ` Austin Obyrne
2014-12-19  9:50                 ` Austin Obyrne
2014-12-19 10:18                   ` MM
2014-12-19 16:49                     ` Denis McMahon
2014-12-20 16:57                       ` Dennis Lee Bieber
2014-12-20 22:15  4%                     ` MM
2015-05-27 14:35  5% Prime sieve montgrimpulo
2015-05-27 17:39  0% ` Jeffrey R. Carter
2015-06-12 15:56     Is this a bug in my code or the compiler? David Botton
2015-06-13 13:33     ` Jacob Sparre Andersen
2015-06-13 15:15       ` J-P. Rosen
2015-06-13 16:43  4%     ` Jacob Sparre Andersen
2015-06-28 14:06     How to shuffle/jumble letters of a given word? Trish Cayetano
2015-06-29 20:21  4% ` Austin Obyrne
2015-06-30 12:29  5% ` Austin Obyrne
2015-07-01 10:40  0%   ` darkestkhan
2015-07-11 15:14  5% After typing input of Integer it SKIPS getting the inputs of String Trish Cayetano
2015-07-11 15:36  0% ` Niklas Holsti
2015-07-11 18:05  4% ` Jeffrey R. Carter
2015-07-17 15:47     Error "exception not permitted here" when putting EXCEPTION in a loop Trish Cayetano
2015-07-17 15:58     ` G.B.
2015-07-18  8:14  5%   ` Trish Cayetano
2015-07-18 10:08         ` Björn Lundin
2015-07-18 12:41  5%       ` Trish Cayetano
2015-07-18 13:56  4%         ` Björn Lundin
2015-07-18 14:08  0%           ` Niklas Holsti
2015-07-18 14:32  5%           ` Trish Cayetano
2015-07-18 14:59  5%             ` Björn Lundin
2015-11-22  3:31  4% How to get a 2D arrays range? John Smith
2015-11-22  7:09  0% ` Niklas Holsti
2016-05-12 11:36  5% Ada.Strings.Fixed.Count raises Storage_Error Xavier Petit
2016-05-12 15:22  0% ` Tero Koskinen
2016-05-12 22:05  0% ` Georg Bauhaus
2016-06-26 21:18  0%   ` Victor Porton
2016-06-27 12:52  0%     ` Victor Porton
2016-05-12 22:56  0% ` Randy Brukardt
2016-06-18 22:52     Generic Embedded List Nodes Warren
2016-06-19  2:14     ` Jeremiah
2016-06-19  2:21       ` Warren
2016-06-19  2:50         ` Warren
2016-06-19  4:45           ` Simon Wright
2016-06-19 18:27  4%         ` Warren
2016-06-19 19:04  0%           ` Dmitry A. Kazakov
2016-06-19 20:13                 ` Warren
2016-06-19 20:35                   ` Dmitry A. Kazakov
2016-06-20  2:42                     ` Warren
2016-06-20  7:25                       ` Dmitry A. Kazakov
2016-06-20 12:26                         ` Warren
2016-06-20 19:33                           ` Niklas Holsti
2016-06-21  2:20                             ` Warren
2016-06-21  5:52                               ` Niklas Holsti
2016-06-21 10:31                                 ` Warren
2016-06-21 21:38                                   ` Niklas Holsti
2016-06-23  2:12                                     ` Warren
2016-06-23  8:19  2%                                   ` Niklas Holsti
2016-08-20 22:41     Why does this input get "skipped"? John Smith
2016-08-20 23:16  4% ` Jeffrey R. Carter
2016-08-21  0:01  4%   ` John Smith
2016-08-21  0:36  0%     ` John Smith
2016-08-21  0:50  0%     ` Jeffrey R. Carter
2016-08-21  1:04  4%       ` John Smith
2016-08-21  4:07  0%         ` Jeffrey R. Carter
2016-09-13  8:46     Question on bounded / unbounded strings Arie van Wingerden
2016-09-14 11:23  4% ` Arie van Wingerden
2016-09-21 22:05     New to Ada need help implementing Warshall's algorithm James Brewer
2016-09-26 17:38  4% ` James Brewer
2016-09-26 18:29  0%   ` Stephen Leake
2016-09-30 22:27     Passing a 2d array into a package and returning the same processed 2d back to main diane74
2016-10-03 18:36  3% ` James Brewer
2016-10-03 19:43       ` Björn Lundin
2016-10-03 21:59         ` James Brewer
2016-10-04 11:29           ` Brian Drummond
2016-10-05 16:16             ` James Brewer
2016-10-05 17:19  3%           ` James Brewer
2017-02-03 20:27  5% I am not understanding user defined exceptions patrick
2017-02-04  1:26  5% ` Dennis Lee Bieber
2017-02-04  9:55  2% Question: Ordered Loading of an Array Austin Obyrne
2017-02-04 12:41  0% ` AdaMagica
2017-02-04 15:34  0%   ` Austin Obyrne
2017-03-09 13:45  4% Getting the index for an element in mutually referencing containers Mart van de Wege
2017-09-14 19:41  4% using a type record's components: Mace Ayres
2017-10-17  4:58     How to make tasks to run in parallel reinert
2017-10-17  6:17  4% ` Per Sandberg
2018-04-06 17:20     Standard."-" provided to "with function "-" (VAL1 : in VALUE_TYPE) return VALUE_TYPE is <>;" refused: Mehdi Saada
2018-04-06 20:09  4% ` Mehdi Saada
2018-05-21 15:23  5% Should exceeding the range of Integer wrap around a la C? nrs5134
2018-05-21 15:45  0% ` Anh Vo
2018-05-29 19:41     Memory pools John Perry
2018-05-31 19:28  4% ` gorgelo
2018-05-31 19:33  3% ` gorgelo
2019-07-27  7:32  5% ambiguous expression (cannot resolve "Put") cryintothebluesky
2019-07-27  8:28  0% ` J-P. Rosen
2019-10-04 18:53  5% GNAT: no visible subprogram matches the specification for "Put" Vincent Marciante
2019-10-05 10:50  0% ` Stephen Leake
2020-06-06 23:40  3% CONSTRAINT ERROR: erroneous memory access jcupak
2020-06-07 15:53  0% ` Anh Vo
2021-02-07  9:15  2% compiler confusion, overloading and "subtype mark required in this context" Mehdi Saada
2021-04-27 14:04  6% Constraint error overflow Richard Iswara
2021-08-26  5:36  5% Get_Line skip input Richard Iswara
2021-08-26  7:56  0% ` Niklas Holsti
2021-08-26  9:09  3% ` Jeffrey R. Carter
2021-08-27  2:55  0%   ` Richard Iswara
2023-07-27  5:26     When using the Ada Big_Numbers.Big_Integers package, can the To_String function output be sliced? Kenneth Wolcott
2023-07-27  8:53     ` Jeffrey R.Carter
2023-07-27 22:47  4%   ` Kenneth Wolcott
2023-07-28 18:21         ` Simon Wright
2023-07-29 11:07           ` AdaMagica
2023-07-29 23:49             ` Kenneth Wolcott
2023-07-29 23:53  5%           ` Kenneth Wolcott
2023-07-30  4:43  4%             ` Randy Brukardt
2023-09-23 20:22  4% Valid attribute and input operations Maciej Sobczak

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox