# Homework 8

*Due by 11:59pm on Wednesday, 7/27*

## Instructions

Download hw08.zip. Inside the archive, you will find a file called hw08.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. See Lab 0 for 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:

Our course uses a custom version of Scheme (which you will build for Project 4) included in the starter ZIP archive. To start the interpreter, type

`python3 scheme`

. To run a Scheme program interactively, type`python3 scheme -i <file.scm>`

. To exit the Scheme interpreter, type`(exit)`

.

### Hinting

Homework 8 includes a hinting sytem that generates hints
specifically for your submitted code. If you ever find yourself stuck, you can
ask for hints by using adding the `--hint`

flag to the ok command.

```
$ python3 ok -q pow --hint
...
Hint: There are extra parentheses on line ...
```

The system tries to generate hints specific to your program by applying multiple techniques, including:

- simple pattern matching
- program verification
- program synthesis

### Question 1

Define the procedures `cadr`

and `caddr`

, which return the second
and third elements of a list, respectively:

```
(define (cddr s)
(cdr (cdr s)))
(define (cadr s)
'YOUR-CODE-HERE
nil
)
(define (caddr s)
'YOUR-CODE-HERE
nil
)
```

Use OK to unlock and test your code:

```
python3 ok -q cadr-caddr -u
python3 ok -q cadr-caddr
```

### Question 2

Implement a procedure called `ordered?`

, which takes a list of numbers and
returns `True`

if the numbers are in nondescending order, and `False`

otherwise.

Hint: The built-in`null?`

function returns whether its argument is`nil`

.

```
(define (ordered? s)
'YOUR-CODE-HERE
nil
)
```

Use OK to unlock and test your code:

```
python3 ok -q ordered -u
python3 ok -q ordered
```

### Question 3

Implement the procedure `nodots`

, which takes a nested list of numbers that
may not be well-formed and returns a nested list with the same content and
structure, but which does not have any dots when displayed. Lists are not
well-formed if they do not properly terminate in a null list. In such cases,
the list will print with a dot before the final item to indicate that its
last two items are contained in a single pair. For example,

`(cons 1 (cons 2 3))`

would print as

`(1 2 . 3)`

for which `nodots`

should substitute

`(1 2 3)`

You may find the built-in

`null?`

and`pair?`

predicates useful.

```
(define (nodots s)
'YOUR-CODE-HERE
nil
)
```

Use OK to unlock and test your code:

```
python3 ok -q nodots -u
python3 ok -q nodots
```

### Sets as Ordered Lists

One way to represent a set is by using an ordered list, where the ordering is used to speed up search (although only by a constant factor). The following few questions explore this idea, assuming a "set" is a Scheme list with no repeated elements that is already ordered from least to greatest.

### Question 4

Define `contains?`

, which returns whether a set `s`

contains value `v`

. The
Python implementation of this procedure is provided for your reference.

```
; Sets as sorted lists
(define (empty? s) (null? s))
(define (contains? s v)
(cond ((empty? s) false)
'YOUR-CODE-HERE
(else nil) ; replace this line
))
; Equivalent Python code, for your reference:
;
; def empty(s):
; return s is Link.empty
;
; def contains(s, v):
; if empty(s):
; return False
; elif s.first > v:
; return False
; elif s.first == v:
; return True
; else:
; return contains(s.rest, v)
```

Use OK to unlock and test your code:

```
python3 ok -q contains -u
python3 ok -q contains
```

### Question 5

Define `add`

, which takes a set `s`

and a value `v`

as arguments. It returns a
representation of a set containing the values in `s`

and the value `v`

. There
should be no repeated elements in the return value.

```
(define (add s v)
(cond ((empty? s) (list v))
'YOUR-CODE-HERE
(else nil) ; replace this line
))
```

Use OK to unlock and test your code:

```
python3 ok -q add -u
python3 ok -q add
```

### Question 6

Define `intersect`

, which returns a set containing only values that appear in
both sets `s`

and `t`

. Your implementation should run in linear time in the
length of the input sets. A Python implementation of this procedure is
provided for your reference.

Also, define `union`

, which returns a set containing all values that appear
in either set `s`

or `t`

.

```
(define (intersect s t)
(cond ((or (empty? s) (empty? t)) nil)
'YOUR-CODE-HERE
(else nil) ; replace this line
))
; Equivalent Python code, for your reference:
;
; def intersect(set1, set2):
; if empty(set1) or empty(set2):
; return Link.empty
; else:
; e1, e2 = set1.first, set2.first
; if e1 == e2:
; return Link(e1, intersect(set1.rest, set2.rest))
; elif e1 < e2:
; return intersect(set1.rest, set2)
; elif e2 < e1:
; return intersect(set1, set2.rest)
(define (union s t)
(cond ((empty? s) t)
((empty? t) s)
'YOUR-CODE-HERE
(else nil) ; replace this line
))
```

Use OK to unlock and test your code:

```
python3 ok -q intersect -u
python3 ok -q intersect
python3 ok -q union -u
python3 ok -q union
```

### Question 7

Another way to represent a set is to store the elements in a binary search tree. A binary search tree's branches are either empty or binary search trees. Also, the entry at the root of the tree must be greater than all entries in the left branch and less than all entries in the right branch.

The following procedures define a data abstraction for a binary search tree.

```
; A data abstraction for binary trees where nil represents the empty tree
(define (tree label left right) (list label left right))
(define (label t) (car t))
(define (left t) (cadr t))
(define (right t) (caddr t))
(define (empty? s) (null? s))
(define (leaf label) (tree label nil nil))
```

Define the procedure `in?`

, which returns whether a binary search tree `t`

contains an element `v`

. Your implementation should run in logarithmic time in
the number of entries in a balanced input tree. The Python implementation of
this procedure is provided for your reference.

```
(define (in? t v)
(cond ((empty? t) false)
'YOUR-CODE-HERE
(else nil)
))
; Equivalent Python code, for your reference:
;
; def contains(t, v):
; if t is BST.empty:
; return False
; elif t.entry == v:
; return True
; elif v < t.entry:
; return contains(t.left, v)
; elif v > t.entry:
; return contains(t.right, v)
```

You can unlock and test using OK:

Use OK to unlock and test your code:

```
python3 ok -q in -u
python3 ok -q in
```

### Question 8

Define `as-list`

, which takes a set (represented with a binary search tree) and
returns a sorted list containing the entries of the tree. For an (optional)
extra challenge, define the procedure so that it runs in linear time in the
length of the resulting list. Converting to and from the sorted list
representation in linear time allows binary search trees to be intersected in
linear time.

```
(define (as-list t)
'YOUR-CODE-HERE
(else nil)
)
```

Use OK to unlock and test your code:

```
python3 ok -q as-list -u
python3 ok -q as-list
```

## Extra Questions: Symbolic Differentiation

Extra questions are not worth extra credit and are entirely optional. They are designed to challenge you to think creatively!

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) (eq? 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) (eq? (car x) '+)))
(define (addend s) (cadr s))
(define (augend 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) (eq? (car x) '*)))
(define (multiplier p) (cadr p))
(define (multiplicand p) (caddr p))
```

### Question 9

Implement `derive-sum`

, a procedure that differentiates a sum by
summing the derivatives of the `addend`

and `augend`

. Use data abstraction
for a sum:

```
(define (derive-sum expr var)
'YOUR-CODE-HERE
)
```

Use OK to unlock and test your code:

```
python3 ok -q derive-sum -u
python3 ok -q derive-sum
```

### Question 10

Implement `derive-product`

, which applies the product
rule to differentiate
products:

```
(define (derive-product expr var)
'YOUR-CODE-HERE
)
```

Use OK to unlock and test your code:

```
python3 ok -q derive-product -u
python3 ok -q derive-product
```

### Question 11

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)`

.

*Hint*: The built-in procedure `expt`

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 (base exp)
'YOUR-CODE-HERE
)
(define (exponent exp)
'YOUR-CODE-HERE
)
(define (exp? exp)
'YOUR-CODE-HERE
)
(define x^2 (make-exp 'x 2))
(define x^3 (make-exp 'x 3))
```

Use OK to unlock and test your code:

```
python3 ok -q make-exp -u
python3 ok -q make-exp
```

### Question 12

Implement `derive-exp`

, which uses the power
rule to derive
exps:

```
(define (derive-exp exp var)
'YOUR-CODE-HERE
)
```

Use OK to test your code:

`python3 ok -q derive-exp`