Line Filters in Ada

Here’s the translation of the Go line filter program to Ada, with explanations in Markdown format suitable for Hugo:

A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.

Here’s an example line filter in Ada that writes a capitalized version of all input text. You can use this pattern to write your own Ada line filters.

with Ada.Text_IO;
with Ada.Characters.Handling;
with Ada.Strings.Unbounded;

procedure Line_Filter is
   use Ada.Text_IO;
   use Ada.Characters.Handling;
   use Ada.Strings.Unbounded;

   Input_Line : Unbounded_String;
begin
   -- Read input lines until end of file
   while not End_Of_File loop
      Input_Line := To_Unbounded_String(Get_Line);
      
      -- Convert the line to uppercase
      declare
         Upper_Line : String := To_Upper(To_String(Input_Line));
      begin
         -- Write out the uppercased line
         Put_Line(Upper_Line);
      end;
   end loop;
exception
   -- Check for errors during input/output operations
   when Error : others =>
      Put_Line(Standard_Error, "Error: " & Exception_Message(Error));
      Set_Exit_Status(Failure);
end Line_Filter;

In this Ada version:

  1. We use the Ada.Text_IO package for input/output operations.
  2. Ada.Characters.Handling provides the To_Upper function for converting strings to uppercase.
  3. Ada.Strings.Unbounded is used for handling variable-length strings.

The main loop reads lines from standard input using Get_Line until it reaches the end of file. Each line is converted to uppercase using To_Upper and then printed to standard output with Put_Line.

Error handling is done using an exception handler. If any error occurs during the execution, it will be caught, printed to standard error, and the program will exit with a failure status.

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then compile and use the line filter to get uppercase lines.

$ gnatmake line_filter.adb
$ cat /tmp/lines | ./line_filter
HELLO
FILTER

This Ada implementation provides the same functionality as the original Go program, reading input line by line, converting each line to uppercase, and writing the result to standard output.