Homework 6: Scheme
Due by 11:59pm on Wednesday, August 4
Instructions
Download hw06.zip. Inside the archive, you will find a file called
hw06.scm, along with a copy of the ok
autograder.
Submission: When you are done, submit with python3 ok
--submit
. You may submit more than once before the deadline; only the
final submission will be scored. Check that you have successfully submitted
your code on okpy.org. See Lab 0 for more instructions on
submitting assignments.
Using Ok: If you have any questions about using Ok, please refer to this guide.
Readings: You might find the following references useful:
Grading: Homework is graded based on correctness. Each incorrect problem will decrease the total score by one point. There is a homework recovery policy as stated in the syllabus. This homework is out of 3 points.
You may find it useful to try code.cs61a.org/scheme when working through problems, as it can draw environment and box-and-pointer diagrams and it lets you walk your code step-by-step (similar to Python Tutor). Don't forget to submit your code through Ok though!
Scheme Editor
As you're writing your code, you can debug using the Scheme Editor. In your scheme
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.
If you find that your code works in the online editor but not in your own interpreter, it's possible you have a bug in code from an earlier part that you'll have to track down. Every once in a while there's a bug that our tests don't catch, and if you find one you should let us know!
Required Questions
Scheme
Assignment Hint Videos
Q1: Thane of Cadr
Define the procedures cadr
and caddr
, which return the second
and third elements of a list, respectively:
; Question 1
;
(define (cddr s)
(cdr (cdr s)))
(define (cadr s)
'YOUR-CODE-HERE
)
(define (caddr s)
'YOUR-CODE-HERE
)
Use Ok to unlock and test your code:
python3 ok -q cadr-caddr -u
python3 ok -q cadr-caddr
Q2: Pow
Implement a procedure pow
for raising the number base
to the power of a
nonnegative integer exp
for which the number of operations grows logarithmically, rather than linearly (the number of recursive calls should be much smaller than the input exp
). For example, for (pow 2 32)
should take 5 recursive calls rather than 32 recursive calls. Similarly, (pow 2 64)
should take 6 recursive calls.
Hint: Consider the following observations:
- x2y = (xy)2
- x2y+1 = x(xy)2
You may use the built-in predicates
even?
andodd?
. Scheme doesn't support iteration in the same manner as Python, so consider another way to solve this problem.
; Question 2
;
(define (square x) (* x x))
(define (pow base exp)
'YOUR-CODE-HERE
)
Use Ok to unlock and test your code:
python3 ok -q pow -u
python3 ok -q pow
Scheme Lists
Assignment Hint Videos
Q3: Filter Lst
Write a procedure filter-lst
, which takes a predicate func
and a list lst
, and
returns a new list containing only elements of the list that satisfy the
predicate. The output should contain the elements in the same order that they
appeared in the original list.
Note: Make sure that you are not just calling the built-in filter
function in Scheme - we are asking you to re-implement this!
; Question 3
;
(define (filter-lst func lst)
'YOUR-CODE-HERE
)
;;; Tests
(define (even? x)
(= (modulo x 2) 0))
(filter-lst even? '(0 1 1 2 3 5 8))
; expect (0 2 8)
Use Ok to unlock and test your code:
python3 ok -q filter_lst -u
python3 ok -q filter_lst
Q4: Accumulate
Fill in the definition for the procedure accumulate
, which merges the first
n
natural numbers according to the following parameters:
merger
: a function of two argumentsstart
: a number with which to start mergingn
: the number of natural numbers to mergeterm
: a function of one argument that computes the nth term of a sequence
For example, we can find the product of all the numbers from 1 to 5 by
using the multiplication operator as the merger
, and starting our
product at 1:
scm> (define (identity x) x)
scm> (accumulate * 1 5 identity) ; 1 * 1 * 2 * 3 * 4 * 5
120
We can also find the sum of the squares of the same numbers by using the
addition operator as the merger
and square
as the term
:
scm> (define (square x) (* x x))
scm> (accumulate + 0 5 square) ; 0 + 1^2 + 2^2 + 3^2 + 4^2 + 5^2
55
scm> (accumulate + 5 5 square) ; 5 + 1^2 + 2^2 + 3^2 + 4^2 + 5^2
60
You may assume that the merger
will always be commutative: i.e. the order
of arguments do not matter.
Hint: You may find it useful to refer to the recursive implementation of
accumulate
we implemented in Python in HW 2.
; Question 4
;
(define (accumulate merger start n term)
'YOUR-CODE-HERE
)
Use Ok to test your code:
python3 ok -q accumulate
Q5: Without Duplicates
Implement without-duplicates
, which takes a list of numbers lst
as input and returns
a list that has all of the unique elements of lst
in the order that they first
appear, but without duplicates. For example, (without-duplicates (list 5 4 5 4 2 2))
evaluates to (5 4 2)
.
Hints: To test if two numbers are equal, use the =
procedure. To test if
two numbers are not equal, use the not
procedure in combination with =
.
You may find it helpful to use the filter-lst
procedure with a helper lambda
function to use as a filter.
; Question 5
;
(define (without-duplicates lst)
'YOUR-CODE-HERE
)
Use Ok to unlock and test your code:
python3 ok -q without_duplicates -u
python3 ok -q without_duplicates
More Scheme, Tail Recursion
Assignment Hint Videos
Q6: 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)
Q7: Tail Recursive Accumulate
In a previous part of the homework, you implementedaccumulate
in scheme. As a reminder, accumulate
merges
the first n
natural numbers according to the parameters merger
, 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 merger
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-tail
with 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.
; Question 7
;
(define (accumulate-tail merger start n term)
'YOUR-CODE-HERE
)
Use Ok to test your code:
python3 ok -q accumulate-tail
Symbolic Differentiation - Optional Question
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.
Q8: 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)
'YOUR-CODE-HERE
)
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 -u
To test your code, if you are in the local Scheme editor, hit
Test
. You can click on a case, pressRun
, and then use theDebug
andEnvironments
features 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
Q9: 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
ok
tests 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)
'YOUR-CODE-HERE
)
Before you start, check your understanding by running
python3 ok -q derive-product -u
To test your code, if you are in the local Scheme editor, hit
Test
. You can click on a case, pressRun
, and then use theDebug
andEnvironments
features 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
Q10: 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)
'YOUR-CODE-HERE
)
(define (exp? exp)
'YOUR-CODE-HERE
)
(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 -u
To test your code, if you are in the local Scheme editor, hit
Test
. You can click on a case, pressRun
, and then use theDebug
andEnvironments
features 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
Q11: 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)
'YOUR-CODE-HERE
)
Before you start, check your understanding by running
python3 ok -q derive-exp -u
To test your code, if you are in the local Scheme editor, hit
Test
. You can click on a case, pressRun
, and then use theDebug
andEnvironments
features 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
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