Scheme代写 | COMP 3007 – Assignment #4

这个作业是完成Scheme对象、环境相关的编程题

COMP 3007 –
Assignment #4

Question 1
[8 marks] Given the following code:
01| (define (run n)
02| (define (iter x y z)
03| (cond ((= z n) x)
04| ((>= z x) (iter (+ x y)(- y z)(+ z 1)))
05| (else (iter (+ x x)(/ y 2)(+ z 1)))))
06| (if (< n 2)
07| n
08| (iter 0 16 0)))
09|
10| (run 4)
a. [/3 marks] Draw a contour diagram at the start of line 08, before the first call to
iter.
b. [/5 marks] Draw a contour diagram at the start of line 03 during the third
evaluation of iter (ie. before the call to (iter 64 4 3)).
Question 2
[10 marks] Given the following code:
01| (define (f L)
02| (cond ((null? L) ‘())
03| ((< (car L) 0)(cons (* (g (cdr L)) (car L)) (f (cdr L))))
04| (else (cons (car L)(f (cdr L))))))
05|
06| (define (g L)
07| (cond ((null? L) 0)
08| (else (+ (car L)(- (g (cdr L)))))))
09|
10| (f ‘(3 -7 4 2))
a. [/5 marks] Draw a contour diagram during the evaluation of g at the beginning of
line 8 (before g recurses on itself) using lexical (static) scoping rules.
b. [/5 marks] Draw a contour diagram during the evaluation of g at the beginning of
line 8 (before g recurses on itself) using dynamic scoping rules.
Question 3
[10 marks] Given the following code:
01| (define (alpha a)
02| (define z 3)
03| (define (beta b)
04| (define a (+ z b))
05| (+ a (gamma b)))
06| (define (gamma c)
07| (set! a (* z c))
08| a)
09| beta)
10|
11| (define omega (alpha 1))
12| (omega 2)
a. [/6 marks] Draw a contour diagram at the start of line 5 (after calling omega on
line 12, before calling gamma on line 5). Your drawing should assume lexical scope.
b. [/1 mark] What is the output of this code? (Using lexical scoping)
c. [/3 marks] Would this code work using dynamic scope as taught in lecture? If yes,
provide the output. If no, explain why not.