On this page:
Understanding Local and Scope
Using Local with Abstractions
Before You Go...

Lab 7 Scoping It Out


Purpose: The purpose of this lab is to practice local and scope.

Textbook References: Chapter 16.2: Local Definitions, Intermezzo: Scope

Understanding Local and Scope

Exercise 1 Complete the following check-expects with the expected value. Run them to double check your answers. Hint: a good first step would be to provide the signatures for the given functions.

(define (f x y z)
  (local [(define x (+ y z))]
    (local [(define y z)]
      (local [(define z (* x y))]
        (+ x y z)))))
(check-expect (f 1 2 3) __)
(define (g a b)
  (+ (local [(define b (string->number a))]
       (local [(define a (sqr b))]
         (- a b)))
     (string-length a)
     (if b 10 5)))
(check-expect (g "5" true) __)

Exercise 2 Design the function adder which, given a Number produces a function that adds that Number to a given Number. Some check-expects have been provided for you below:
(check-expect ((adder 3) 4) 7)
(check-expect ((adder 10) 2) 12)

Using Local with Abstractions

You should use a pre-defined list abstraction to complete each of the following exercises. Each exercise can be completed with the use of only one abstraction.

Exercise 3 Design the function add-to-all which, given a list of numbers and a Number, adds that number to each element of the list. For example, (add-to-all (list 1 2 3) 7) would produce (list 8 9 10).

Exercise 4 Design the function remove-all-matches which is given three inputs: a list, a single element to look for, and an equality function. It then removes any element of the list that is equivalent to the given element using the given equality function.

Exercise 5 Design the function add-all-matches which is given the same three inputs as the previous function. It then duplicates any element that is equivalent to the given element. For example, (add-all-matches (list 1 2 1) 1 =) would produce (list 1 1 2 1 1).

Before You Go...

If you had trouble finishing any of the exercises in the lab or homework, or just feel like you’re struggling with any of the class material, please feel free to come to office hours and talk to a TA or tutor for additional assistance.