Principles of Programming Languages — Homework 14

Due by class time Friday, November 19

Reading

Tester Program

To use the auto-tester program for this assignment, download the files hw14-tester.scm and auto-tester.scm and put them in the same folder as your Scheme file. (If you've already downloaded auto-tester.scm before, you don't need to download it again.) Then put (require "hw14-tester.scm") at the top of your Scheme file.

Exercises

  1. Add while-loops to your language, with the following syntax:

    (while condition : body ...)
    

    One or more body expressions may appear after the : symbol. To evaluate a while, the condition expression is first evaluated in the current environment. If the result is true, each body expression is evaluated in order, and then the cycle repeats, until condition becomes false, at which point the loop terminates and returns the symbol done as the final result. For example:

    ==> (with [x = 3] :
          (while (x > 0) :
             (print x)
             (x := (x - 1))))
    3
    2
    1
    done
    
    ==> (with [n = 12] [count = 0] :
          (while (n > 1) :
            (print n)
            (if ((n % 2) == 0)
                then (n := (n / 2))
                else (n := ((3 * n) + 1)))
            (count := (count + 1)))
          (print "reached 1 after" count "steps"))
    12 
    6 
    3 
    10 
    5 
    16 
    8 
    4 
    2 
    reached 1 after 9 steps 
    done
    

    Autotester cases: (test: run 1 2 3 4 5)


  2. Add for-loops to your language, with the following syntax:

    (for var in exp : body ...)
    

    One or more body expressions may appear after the : symbol. To evaluate a for loop, exp is evaluated once. The result should be a list (if it isn't, your interpreter should generate an appropriate error message). Then, on each cycle of the loop, var is bound to the next element of the list in turn, and the body expressions are evaluated in order. The final value returned is the symbol done. Examples:

    ==> (for n in (list 1 2 3 4) : (print (n * n)))
    1
    4
    9
    16
    done
    
    ==> (with [total = 0] :
          (for x in (list 1 2 3 4 5) :
             (print "x is" x)
             (total := (total + x))
             (print "total is" total)))
    x is 1 
    total is 1 
    x is 2 
    total is 3 
    x is 3 
    total is 6 
    x is 4 
    total is 10 
    x is 5 
    total is 15 
    done
    
  3. Autotester cases: (test: run 6 7 8 9 10)


Turning in Your Homework