% Here are some sample code in Postscript % Note: any text after percent symbol and the end of the line % is a comment % How to use: % 1. Cut and paste each sample code into a separate file. % Let's take the second example and save it to a file called "t2.mps". % 2. Load support code into SML: use "hw2support.sml"; % Call the parser: parse "t2.mps"; % Study the output to understand how a piece of postscript code is parsed. % 3. If you write your "interp", then you can test whether it interprets % correctly: interp "t2.mps"; % you should see a question mark ?, which is to prompt you for input. % Say, you type 5 and return. You should see >>> 15 %example code 1: /sub {neg add} def 7 4 sub %example code 2: % sum is a recursive procedure that takes a natural number n % and return the summation of all natural numbers from 1 to n /sum { dup 1 eq {} {dup -1 add sum add} ifelse } def % A number is taken from the keyboard and saved onto the stack. % The procedure "sum" is executed on that number and the result % is written to the screen read sum write %example code 3: % A procedure "mul" is defined, which takes two integers % and multiply them and return the product. /sum { dup 1 eq {} {dup -1 add sum add} ifelse } def /mul { begin /y exch def /x exch def /sum 0 def { y 0 eq {exit} {} ifelse /sum sum x add def /y y -1 add def } loop sum end } def % Take two integers from the keyboard, call "mul" and write the result % to the screen. read read mul write %example code 4: % A recursive procedure for calculating a factorial. /sum { dup 1 eq {} {dup -1 add sum add} ifelse } def /mul { begin /y exch def /x exch def /sum 0 def { y 0 eq {exit} {} ifelse /sum sum x add def /y y -1 add def } loop sum end } def /fact { begin /n exch def n 0 eq {1} {n n -1 add fact mul} ifelse end } def read fact write