Arithmetic evaluation: Difference between revisions

m
→‎{{header|Ada}}: added code highlighting
m (→‎{{header|D}}: AST is built & remove incorrect tag)
m (→‎{{header|Ada}}: added code highlighting)
Line 11:
This example is produced in several packages. The first package provides a simple generic stack implementation employing a controlled type. Controlled types are automatically finalized during assignment and when the variable goes out of scope.
 
<ada>with Ada.Finalization;
generic
type Element_Type is private;
Line 40:
procedure Finalize(Object : in out Stack);
end Generic_Controlled_Stack;</ada>
 
The type Ada.Finalization.Controlled is an abstract type. The Finalize procedure is overridden in this example to provide automatic clean up of all dynamically allocated elements in the stack. The implementation of the package follows:
 
<ada>with Ada.Unchecked_Deallocation;
with Ada.Text_IO; use Ada.Text_IO;
Line 126:
end Finalize;
end Generic_Controlled_Stack;</ada>
 
The next little package gets the tokens for the arithmetic evaluator.
 
<ada>with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package Arithmetic_Tokens is
Line 137:
Token : out Unbounded_String;
End_Index : out Positive);
end Arithmetic_Tokens;</ada>
 
Again, the most interesting parts are in the package body.
 
<ada>package body Arithmetic_Tokens is
---------------
Line 190:
end Get_token;
end Arithmetic_Tokens;</ada>
Finally, we come to the arithmetic evaluator itself. This approach first converts the infix formula into a postfix formula. The calculations are performed on the postfix version.
 
<ada>with Ada.Text_Io; use Ada.Text_Io;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Generic_Controlled_Stack;
Line 323:
begin
Put_line("(3 * 50) - (100 / 10)= " & Integer'Image(Calculate("(3 * 50) - (100 / 10)")));
end Arithmetic_Evaluator;</ada>
 
=={{header|C++}}==
Anonymous user