home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / modula2 / library / modula1 / postfix.mod < prev    next >
Text File  |  1987-06-11  |  1KB  |  59 lines

  1. (* Convert expressions from infix to postfix form.  Each
  2.    expression is written on a separate line.  Expressions
  3.    have the following syntax:
  4.  
  5.       expression = term {("+"|"=") term}.
  6.       term =       factor {"*" factor}.
  7.       factor =     letter | "(" expression ")". *)
  8.  
  9. MODULE postfix;
  10.  
  11. FROM InOut IMPORT Read, Write, WriteLn, Done, OpenInput;
  12.  
  13. VAR ch: CHAR;
  14.  
  15. PROCEDURE expression;
  16. VAR op: CHAR;
  17.  
  18.   PROCEDURE factor;
  19.   BEGIN
  20.     IF ch = '(' THEN
  21.       Read(ch);
  22.       expression;
  23.       Read(ch);
  24.     ELSE
  25.       Write(ch); Read(ch)
  26.     END
  27.   END factor;
  28.  
  29.   PROCEDURE term;
  30.   BEGIN
  31.     factor;
  32.     WHILE ch = '*' DO
  33.       Read(ch);
  34.       factor;
  35.       Write('*');
  36.     END
  37.   END term;
  38.  
  39. BEGIN
  40.   term;
  41.   WHILE (ch = '+') OR (ch = '-') DO
  42.     op := ch;
  43.     Read(ch);
  44.     term;
  45.     Write(op);
  46.   END
  47. END expression;
  48.  
  49. BEGIN
  50.   OpenInput('TEXT');
  51.   LOOP
  52.     Write(' ');
  53.     Read(ch);
  54.     IF NOT Done THEN EXIT END;
  55.     expression;
  56.     WriteLn;
  57.   END
  58. END postfix.
  59.