Exercises for Lesson 19
Exercise 1: Currying, revisited
Understanding closures can help you really internalize what’s happening with currying. Consider this Scheme program:
(define curried-add
(lambda (a)
(lambda (b)
(+ a b))))
(define add-ten (curried-add 10))
(add-ten 9)Draw a diagram with frames and closures based on evaluating this program.
Exercise 2: lambda + if
Consider the following Scheme program:
(define a 2)
(define f
(lambda (b c)
(if (> b a)
(+ b c)
(+ a c))))
(f 5 1)Draw a diagram with frames and closures based on evaluating this program.
Exercise 3: lazy lists
Go back and look at your code for the Lazy Lists assignment. Can you draw diagrams with frames and closures for the various procedures you implemented?
Exercise 4: set!
Recall that, by convention, a Scheme procedure with side effects has a name ending in !. The procedure (set! var expr) behaves as follows: it evaluates expr in the current environment and then binds the result of evaluating expr to var wherever it exists in the environment (the current frame or one of its ancestors), or in the global environment if var is not already bound.
Given this explanation, draw a diagram with frames and closures for the following program, and determine what it evaluates to:
(define a 3)
(define f
(lambda (b c)
(if (> b a)
(+ b c)
(+ a c))))
(set! a 1)
(let [(a 4)] (f 15 9))
Exercise 5: set! vs. define
You get the same result from the following two Scheme programs:
(set! a 1)
a(define a 1)
aWhat is an example of when replacing set! with define causes evaluation to be different? Use environment and closure diagrams to illustrate the difference.