Search code examples
adaada2012

How to add different type values to an array in Ada?


My goal is to receive from standard input an equation, store that in an array for later use/re-printing, then output a line printing the whole equation AND the answer after just like so:

Input: 2+3=

Output: 2 + 3 = 5

I am very confused on how to go about doing this due to the inability of Ada to have dynamic strings and such.

This is a rough idea that I have in pseudo-code..

 Until_loop:                 
       loop 

         get(INT_VAR);
         --store the int in the array?
         get(OPERATOR_VAR);
         --store the operator in the following index of that array? and
         --repeat until we hit the equal sign, signaling end of the equation

         get(CHECK_FOR_EQUALSIGN);
     exit Until_loop when CHECK_FOR_EQUALSIGN = "=";

     end loop Until_loop;

 --now that the array is filled up with the equation, go through it and do the math
 --AND print out the equation itself with the answer

I am guessing the array should look like:

[2][+][5][=][7]

I am also a beginner with Ada, so it's even more difficult to get a grasp of things, I am very good with Java, but I can't get used to the strongly typed syntax. Please ask if you need more info.


Solution

  • Ada can use dynamic fixed strings, without resorting to Unbounded_String or Containers, or allocation and pointers, although these are options.

    The insight making this possible is that a string can get its size from its initialisation expression when it is declared - but that declaration can be inside a loop, so that it is executed anew each time round the loop. You can't always structure a program so that this makes sense, though it's possible surprisingly often, with a little thought.

    Another feature is that later on, these "declare" blocks make great candidates for very easy refactoring into procedures.

    with Ada.Text_IO; use Ada.Text_IO;
    
    procedure Calculator is
    begin
       loop
          Put("Enter expression: ");
          declare
             Expression : String := Get_Line;
          begin
             exit when Expression = "Done";
             -- here you can parse the string character by character
             for i in Expression'range loop
                put(Expression(i));
             end loop;
             New_Line;
          end;
       end Loop;
    end Calculator;
    

    You should get

    brian@Gannet:~/Ada/Play$ gnatmake calculator.adb
    gcc-4.9 -c calculator.adb
    gnatbind -x calculator.ali
    gnatlink calculator.ali
    brian@Gannet:~/Ada/Play$ ./calculator
    Enter expression: hello
    hello
    Enter expression: 2 + 2 =
    2 + 2 =
    Enter expression: Done
    brian@Gannet:~/Ada/Play$ 
    

    You still have to write the calculator...