Homework 8 Solutions
Solution Files
You can find the solutions in hw08.scm.
Deadline Extension
Important: The deadline for this homework assignment has been extended until Friday, 4/16 at 9AM Pacific Time. To receive credit for this homework, make sure to complete all of the questions below and run python ok --submit before the new deadline.
Scheme Editor
How to launch
In your hw08 folder you will find a new editor. To run this editor, run python3 editor. This should pop up a window in your browser; if it does not, please navigate to localhost:31415 and you should see it.
Make sure to run python3 ok in a separate tab or window so that the editor keeps running.
Features
The hw08.scm file should already be open. You can edit this file and then run Run to run the code and get an interactive terminal or Test to run the ok tests.
Environments will help you diagram your code, and Debug works with environments so you can see where you are in it. We encourage you to try out all these features.
Reformat is incredibly useful for determining whether you have parenthesis based bugs in your code. You should be able to see after formatting if your code looks weird where the issue is.
By default, the interpreter uses Lisp-style formatting, where the parens are all put on the end of the last line
(define (f x) (if (> x 0) x (- x)))However, if you would prefer the close parens to be on their own lines as so
(define (f x) (if (> x 0) x (- x) ) )you can go to Settings and select the second option.
Required Questions
Assignment Hint Videos
Problem 1:
Problem 2:
Problem 3 + 4:
Q1: WWSD: Quasiquote
Use Ok to test your knowledge with the following "What Would Scheme Display?" questions:
python3 ok -q wwsd-quasiquote -u
scm> '(1 x 3)
______(1 x 3)
scm> (define x 2)
______x
scm> `(1 x 3)
______(1 x 3)
scm> `(1 ,x 3)
______(1 2 3)
scm> '(1 ,x 3)
______(1 (unquote x) 3)
scm> `(,1 x 3)
______(1 x 3)
scm> `,(+ 1 x 3)
______6
scm> `(1 (,x) 3)
______(1 (2) 3)
scm> `(1 ,(+ x 2) 3)
______(1 4 3)
scm> (define y 3)
______y
scm> `(x ,(* y x) y)
______(x 6 y)
scm> `(1 ,(cons x (list y 4)) 5)
______(1 (2 3 4) 5)
Tail Recursion
Q2: Tail Recursive Accumulate
In Homework 7, you implementedaccumulate in scheme. As a reminder, accumulate combines
the first n natural numbers according to the parameters combiner, start, n, and term.
You can refer to your implementation of accumulate as a reminder of what the function does and a refresher of its implementation.
Update your implementation of accumulate to be tail recursive. It
should still pass all the tests for "regular" accumulate!
You may assume that the input combiner and term procedures are
properly tail recursive.
If your implementation for accumulate in the previous question is already
tail recursive, you may simply copy over that solution (replacing accumulate
with accumulate-tail as appropriate).
If you're running into an recursion depth exceeded error and you're using the staff interpreter, it's very likely your solution is not properly tail recursive.
We test that your solution is tail recursive by calling
accumulate-tailwith a very large input. If your solution is not tail recursive and does not use a constant number of frames, it will not be able to successfully run.
(define (accumulate-tail combiner start n term)
(define (accum-helper x so-far)
(if (= x 0)
so-far
(accum-helper (- x 1) (combiner (term x) so-far))
))
(accum-helper n start))
; ALT solution
(define (accumulate-tail combiner start n term)
(if (= n 0)
start
(accumulate-tail combiner (combiner (term n) start) (- n 1) term)))
Use Ok to test your code:
python3 ok -q accumulate-tail
If we were to implement this iteratively in Python, it might look something like:
def accumulate(combiner, start, n, term):
total = start
while n > 0:
total = combiner(total, term(n))
n -= 1
return total
With that in mind, we can create a helper function in Scheme to help us track a running total. This will be updated in each recursive call.
The alternative solution simply uses the start value to track all the
values we've used so far, but it effectively functions the same.
Symbolic Differentiation
The following problems develop a system for
symbolic differentiation
of algebraic expressions. The derive Scheme procedure takes an
algebraic expression and a variable and returns the derivative of the
expression with respect to the variable. Symbolic differentiation is of
special historical significance in Lisp. It was one of the motivating
examples behind the development of the language. Differentiating is a
recursive process that applies different rules to different kinds of
expressions.
; derive returns the derivative of EXPR with respect to VAR
(define (derive expr var)
(cond ((number? expr) 0)
((variable? expr) (if (same-variable? expr var) 1 0))
((sum? expr) (derive-sum expr var))
((product? expr) (derive-product expr var))
((exp? expr) (derive-exp expr var))
(else 'Error)))
To implement the system, we will use the following data abstraction. Sums and products are lists, and they are simplified on construction:
; Variables are represented as symbols
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eqv? v1 v2)))
; Numbers are compared with =
(define (=number? expr num)
(and (number? expr) (= expr num)))
; Sums are represented as lists that start with +.
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list '+ a1 a2))))
(define (sum? x)
(and (list? x) (eqv? (car x) '+)))
(define (first-operand s) (cadr s))
(define (second-operand s) (caddr s))
; Products are represented as lists that start with *.
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
(define (product? x)
(and (list? x) (eqv? (car x) '*)))
; You can access the operands from the expressions with
; first-operand and second-operand
(define (first-operand p) (cadr p))
(define (second-operand p) (caddr p))
Note that we will not test whether your solutions to this question correctly apply the chain rule. For more info, check out the extensions section.
Q3: Derive Sum
Implement derive-sum, a procedure that differentiates a sum by
summing the derivatives of the first-operand and second-operand. Use data abstraction
for a sum.
Note: the formula for the derivative of a sum is
(f(x) + g(x))' = f'(x) + g'(x)
(define (derive-sum expr var)
(make-sum (derive (first-operand expr) var)
(derive (second-operand expr) var)))
The tests for this section aren't exhaustive, but tests for later parts will fully test it.
Before you start, check your understanding by running
python3 ok -q derive-sum -uTo test your code, if you are in the local Scheme editor, hit
Test. You can click on a case, pressRun, and then use theDebugandEnvironmentsfeatures to figure out why your code is not functioning correctly.You can also test your code from the terminal by running
python3 ok -q derive-sum
This question is deceptively simple; make sure you understand what the problem is asking!
To derive a sum of values, we simply derive the first-operand (the thing before the +
in normal math) and the second-operand (the thing after the +).
Then, we have to combine the values again using a sum. In some cases, using the sum operator will work; in fact, since we've only implemented derivatives of sums and single variables, we can't do anything too complicated here!
But the correct solution requires the use of make-sum which will helpfully
simplify arithmetic operations and handle symbols. This necessary is for cases
where you have to derive something like the following (after implementing
derive-exp):
scm> (derive (make-sum x^3 x^2) 'x)
(+ (* 3 (^ x 2)) (* 2 x))
Video walkthrough: https://youtu.be/mitrrYe0I8U
Q4: Derive Product
Note: the formula for the derivative of a product is
(f(x) g(x))' = f'(x) g(x) + f(x) g'(x)
Implement derive-product, which applies the product
rule to differentiate
products. This means taking the first-operand and second-operand, and then
summing the result of multiplying one by the derivative of the other.
The
oktests expect the terms of the result in a particular order. First, multiply the derivative of the first-operand by the second-operand. Then, multiply the first-operand by the derivative of the second-operand. Sum these two terms to form the derivative of the original product. In other words,f' g + f g', not some other ordering.
(define (derive-product expr var)
(make-sum
(make-product (derive (first-operand expr) var)
(second-operand expr))
(make-product (first-operand expr)
(derive (second-operand expr) var))))
Before you start, check your understanding by running
python3 ok -q derive-product -uTo test your code, if you are in the local Scheme editor, hit
Test. You can click on a case, pressRun, and then use theDebugandEnvironmentsfeatures to figure out why your code is not functioning correctly.You can also test your code from the terminal by running
python3 ok -q derive-product
Much like the derive-sum, make sure you understand what the problem is asking.
The main hiccup this time is that the derivative rules are a bit more
complicated for products, and will require using products and sums. Just
make sure to use make-sum and make-product, otherwise you may run into
issues further on.
Video walkthrough: https://youtu.be/yanBT57HgXE
Optional Questions
Q5: Make Exp
Implement a data abstraction for exponentiation: a base raised to the
power of an exponent. The base can be any expression, but assume that the
exponent is a non-negative integer. You can simplify the cases when
exponent is 0 or 1, or when base is a number, by returning numbers from
the constructor make-exp. In other cases, you can represent the exp as a
triple (^ base exponent).
You may want to use the built-in procedure
expt, which takes two number arguments and raises the first to the power of the second.
; Exponentiations are represented as lists that start with ^.
(define (make-exp base exponent)
(cond ((= exponent 0) 1)
((= exponent 1) base)
((and (number? base) (integer? exponent)) (expt base exponent))
(else (list '^ base exponent))))
(define (exp? exp)
(and (list? exp) (eqv? (car exp) '^)))
(define x^2 (make-exp 'x 2))
(define x^3 (make-exp 'x 3))
Before you start, check your understanding by running
python3 ok -q make-exp -uTo test your code, if you are in the local Scheme editor, hit
Test. You can click on a case, pressRun, and then use theDebugandEnvironmentsfeatures to figure out why your code is not functioning correctly.You can also test your code from the terminal by running
python3 ok -q make-exp
It may be helpful to refer to code for make-sum and make-prod to see how
they handle some special cases.
- For exponent of 0 or 1, we can return a simplified result.
- If we're doing the exponent of two numbers, we can compute that right away
using
exptinstead of creating an exponent abstraction. This is much likemake-sumandmake-prodwhere we calculate the result using+or*. - Otherwise, we create the exponent abstraction -- a list of the caret
^, base, and exponent.
Video walkthrough: https://youtu.be/4E7bOnITEfc
Q6: Derive Exp
Implement derive-exp, which uses the power
rule to derive exponents. Reduce
the power of the exponent by one, and multiply the entire expression by
the original exponent.
Note: the formula for the derivative of an exponent is
[f(x)^(g(x))]' = f(x)^(g(x) - 1) * g(x), if we ignore the chain rule, which we do for this problem
(define (derive-exp exp var)
(let ((b (first-operand exp))
(n (second-operand exp)))
(if (number? n)
(let ((first (make-product n (make-exp b (- n 1)))))
(make-product first (derive b var))) ;; Note: Chain rule isn't tested by ok.
'unknown)))
Before you start, check your understanding by running
python3 ok -q derive-exp -uTo test your code, if you are in the local Scheme editor, hit
Test. You can click on a case, pressRun, and then use theDebugandEnvironmentsfeatures to figure out why your code is not functioning correctly.You can also test your code from the terminal by running
python3 ok -q derive-exp
Applying the power rule here is fairly straightforward -- it's arguably not much
different from derive-sum or derive-prod. The only real differences are that
we're using the power rule and the result will require using make-exp and
make-prod.
Our solution here also implements the chain rule, but it's not necessary to pass the tests. An implementation that doesn't use the chain rule could just return:
(make-product n (make-exp b (- n 1)))
Video walkthrough: https://youtu.be/bIM1XrwBMKg
Extensions
There are many ways to extend this symbolic differentiation
system. For example, you could simplify nested exponentiation expression such
as (^ (^ x 3) 2), products of exponents such as (* (^ x 2) (^ x 3)), and
sums of products such as (+ (* 2 x) (* 3 x)). You could apply the chain
rule when deriving exponents, so that
expressions like (derive '(^ (^ x y) 3) 'x) are handled correctly. Enjoy!
Submit
Make sure to submit this assignment by running:
python3 ok --submit