Principles of Programming Languages — Homework 8

Due by class time Friday, October 8

Reading

Review the code examples from class today. If you like, you can read more about let-expressions here.

Exercises

  1. Here is our meaning function for infix expressions that we wrote in class:

    (define meaning
      (lambda (exp env)
        (cond
          [(number? exp) exp]
          [(symbol? exp) (lookup exp env)]
          [(and (list? exp) (= (length exp) 3))
           (cond
             [(eq? (operator exp) '+) (+ (meaning (left-side exp) env) (meaning (right-side exp) env))]
             [(eq? (operator exp) '-) (- (meaning (left-side exp) env) (meaning (right-side exp) env))]
             [(eq? (operator exp) '*) (* (meaning (left-side exp) env) (meaning (right-side exp) env))]
             [(eq? (operator exp) '/) (/ (meaning (left-side exp) env) (meaning (right-side exp) env))]
             [else (error "unrecognized operator:" (operator exp))])]
          [else (error "invalid expression:" exp)])))
    

    Rewrite this function using a let-expression to make the code more readable, by giving the result of the recursive call on the left side of exp the name value1 and the result of the recursive call on the right side the name value2. Hint: the let-expression should go immediately before the inner cond.

  2. The good old quadratic formula from high school math is shown below:

    This formula is used to compute the value of x in the equation ax2 + bx + c = 0. There are always two possible values of x (called "roots") that will satisfy the equation, one calculated using addition in place of the ± symbol and the other using subtraction. Write the function (quadratic a b c) that takes the values of a, b, and c as input, and returns both roots in a list. You can use Scheme's built-in sqrt function to compute square roots, but your function should use a let-expression to avoid computing the square root of b2 − 4ac twice. Use another let-expression to give the names x1 and x2 to the individual roots, and return the final result as (list x1 x2). Examples:

    (quadratic 1 3 2)    →  (-1 -2)
    (quadratic -2 -4 0)  →  (-2 0)
    (quadratic 4 -5 1)   →  (1 1/4)
    

  3. Write the function (extend1 var val env) that takes a variable var, a value val, and an environment env as input, and returns a new environment containing a new binding (var val), along with all of the other bindings from env. Example:

    (define env1 '((a 1) (b 2) (c 3)))
    
    (extend1 'x 5 env1)  →  ((x 5) (a 1) (b 2) (c 3))
    

Turning in Your Homework