Reputation: 303
Create a subprogram of type operator that receives two integers and sends them back the negative sum of them. I.e. if the sum is positive it will be the result is negative or if the sum is a negative result positive. Ex. 6 and 4 give -10 as a result and 2 and -6 give 4.
For instance:
Type in two integers: **7 -10**
The negative sum of the two integers is 3.
Type in two integers: **-10 7**
The positive sum of the two integers is -3.
No entries or prints may be made in the subprogram.
So I attempted this task and actually solved it pretty easily using a function but when it came to converting it to an operator I stumbled into a problem.
This is my approach:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Test is
function "+" (Left, Right : in Integer) return Integer is
Sum : Integer;
begin
Sum := -(Left + Right);
return Sum;
end "+";
Left, Right : Integer;
begin
Put("Type in two integers: ");
Get(Left);
Get(Right);
Put("The ");
if -(Left + Right) >= 0 then
Put("negative ");
else
Put("positive ");
end if;
Put("sum of the two integers is: ");
Put(-(Left + Right));
end Test;
My program compiles but when I run it and type two integers it says:
raised STORAGE_ERROR: infinite recursion
How do I solve this problem using an operator? I managed to tackle it easily with the procedure- and function subprogram but not the operator. Any help is appreciated!
Upvotes: 0
Views: 274
Reputation:
You can use the type system to solve this without using a new operator symbol.
As a hint, operators can overload on argument and return types. And a close reading of the question shows the input type is specified, but not the output type. So, how about this?
type Not_Integer is new Integer;
function "+" (Left, Right : in Integer) return Not_Integer is
Sum : Integer;
begin
Sum := -(Left + Right);
return Not_Integer(Sum);
end "+";
As the two "+" operators have different return types, there is no ambiguity between them and no infinite recursion.
You will have to modify the main program to assign the result to a Not_Integer
variable in order to use the new operator.
Upvotes: 3