Image goes here
Homework 1
CptS 355 - Programming Language Design
Washington State University

CptS 355 Homework 1

Assigned: Friday, Sept. 7
Due: Friday, Sept. 14, in class
Preparing your work: all homework must be typed, not handwritten

When you are asked what a piece of code does you might just type it into Ghostscript and report the answer. If you did this you would be missing 80% of the benefit of the problem. Execute the code by hand first, then confirm your answer by checking it on the interpreter.

  1. Suppose the postscript program 3 (3) {3} is executed. What is on the stack at the end?
  2. If we now execute pop eq what is on the stack? Why?
  3. What is wrong with the program
        3 2 eq 4 6 ifelse
    
  4. The previous question illustrates that the ifelse operator is similar to the C's if...else statement in that the operands of ifelse must be code arrays. What if you wanted to simulate C's conditional expression? That is, how would you implement an operator ? such that true 1 2 ? leaves 1 on the stack and false 1 2 ? leaves 2 on the stack?
  5. Consider the program
        /ffib {
    	/n exch def
    	   n 0 eq
    	   {1}
    	   {
    		 n 1 eq
    		 {-1}
    		 {1 -1 n 1 sub fhelp}
    	      ifelse
    	   }
    	ifelse
        } def
    
        /fhelp {
    	/n exch def
    	   n 0 eq
    	   {exch pop}
    	   {
    	       /tos exch def
    	       tos sub
    	       tos exch n 1 sub fhelp
    	   }
    	ifelse
        } def
    
    What are the values of 0 ffib, 1 ffib, 2 ffib, 3 ffib, and 4 ffib?
    (Challenge) Notice that there are no dict and begin operators in this program yet it seems to compute without getting confused. Can you spot the essential difference between this program and the factorial function discussed in class that makes this possible? Even though this code works as is, it would be better to push a new dictionary on the dictionary stack each time a function is called. Revise the code to contain the necessary begin, end and dict operators.
  6. (Challenge) Define a function, rev, that reverses the order of the elements on the operand stack. That is, after 1 2 3 4 5 there is a 5 at the top of the stack and 1 at the bottom. After 1 2 3 4 5 rev the 1 is at the top of the stack and 5 is at the bottom (and the other elements are correspondingly rearranged).
  7. The name of this exercise is "what gets evaluated when?" Consider the code
    /x 5 def
    /f {
          1 dict begin
          /g { /x 4 def } def
          x g x
    } def
    x f x end x
    
    What is on the stack when this program finishes executing?
(c) 2003 Curtis Dyreson, (c) 2004-2006 Carl H. Hauser           E-mail questions or comments to Prof. Carl Hauser