3.2 Example: Expanding TAB Characters

Suppose we want to read a file, expand all TAB characters to space characters, and write the expanded lines to another file. The program which implements this task is shown in Program 3.1.

   fun {Insert N Is}
      if N>then {Insert N-|Is} else Is end 
   fun {Scan Is Tab N}
      case Is of nil then nil
      [] I|Ir then 
         case I  
         of &\t then M=Tab-(N mod Tab) in {Insert M {Scan Ir Tab M+N}}
         [] &\n then I|{Scan Ir Tab 0}
         [] &\b then I|{Scan Ir Tab {Max 0 N-1}}
         else I|{Scan Ir Tab N+1}
   proc {Expand Tab IN ON}
      IF={New Open.file init(name:IN)}  
      OF={New Open.file init(name:ON flags:[write create truncate])}
      {IF read(list:Is size:all)}    {IF close}
      {OF write(vs:{Scan Is Tab 0})} {OF close}

Program 3.1: The Expand procedure.

The file with name IN is opened for reading. After reading the entire file into the list Is, the file and the associated object are closed. Remember that reading the entire file is obtained by giving all as the value for feature size.

The expansion of TAB characters is done in the function Scan. It takes as input parameters the list of characters Is, the Tab, and the current position N in the current line.

The outer case of Scan figures out whether there are characters to process. If the next character to process is a TAB character, enough space characters to reach the next multiple of TabStop are inserted. This is performed by the self explanatory function Insert.

A newline character resets the position N to zero. The position is decremented whenever a backspace character is encountered. Any other character increments the position.

A second file is opened for writing (indicated by write). If a file with name ON does not exist, it is created (indicated by create). Otherwise the already existing file is truncated to length zero (indicated by truncate) and rewritten. The expanded string is written to this file.

The file and its associated file object are closed after writing the expanded list of characters to it.

Christian Schulte
Version 1.4.0 (20080702)