Local bindings

Exercise 1

What are the values of the following let-expressions?

  1. (let ((tone "fa")
          (call-me "al"))
      (string-append call-me tone "l" tone))
    
  2. ;; Solutions to the quadratic equation x^2 - 5x + 4:
    ;;
    (let ((discriminant (- (* -5 -5) (* 4 1 4))))
      (list (/ (+ (- -5) (sqrt discriminant)) (* 2 1))
            (/ (- (- -5) (sqrt discriminant)) (* 2 1))))
    
  3. (let ((total (+ 8 3 4 2 7)))
      (let ((mean (/ total 5)))
        (* mean mean)))
    

You may use DrScheme to help you answer these questions, but be sure you can explain how it arrived at its answers.

Exercise 2

Rewrite the count-all-symbols procedure from the reading on deep recursion, using a let-expression to consolidate repeated subexpressions in the same manner.

Exercise 3

Write a nested let-expression that binds a total of five names, a, b, c, d, and e, with a bound to 9387 and each subsequent name bound to a value twice as large as the one before it -- b should be twice as large as a, c twice as large as b, and so on. The body of the innermost let-expression should compute the sum of the values of the five names.

Exercise 4

Write a let*-expression equivalent to the let-expression in the previous exercise.

Exercise 5

Here is a procedure that takes a non-empty list of strings as argument and returns the longest string on the list (or one of the longest strings, if there is a tie).

(define longest-string-in-list
  (lambda (ls)
    (if (null? (cdr ls))
        (car ls)
        (longer-string (car ls) (longest-string-in-list (cdr ls))))))

This definition of the longest-string-in-list procedure includes a call to the longer-string procedure, which returns the longer of two given strings:

(define longer-string
  (lambda (left right)
    (if (<= (string-length right) (string-length left))
        left
        right)))

Revise the definition of longest-string-in-list so that the name longer-string is bound to the procedure that it denotes only locally, in a let-expression.


This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~gum/courses/151/labs/local-bindings.xhtml

created February 26, 1997
last revised February 13, 2003

John David Stone (stone@cs.grinnell.edu) and Ben Gum (gum@cs.grinnell.edu)