Lab 09: Scheme
Due at 11:59pm on Friday, 10/27/2017.
Starter Files
Download lab09.zip. Inside the archive, you will find starter files for the questions in this lab, along with a copy of the Ok autograder.
Submission
By the end of this lab, you should have submitted the lab with
python3 ok submit
. You may submit more than once before the
deadline; only the final submission will be graded.
Check that you have successfully submitted your code on
okpy.org.
 To receive credit for this lab, you must complete Question 1 through 4 in lab09.scm and submit through Ok.
 Questions 5 through 11 are extra practice. They can be found in the lab09_extra.scm file. It is recommended that you complete these problems on your own time.
Topics
Scheme
Scheme is a famous functional programming language from the 1970s. It is a dialect of Lisp (which stands for LISt Processing). The first observation most people make is the unique syntax, which uses a prefix notation and (often many) nested parentheses (see http://xkcd.com/297/). Scheme features firstclass functions and optimized tailrecursion, which were relatively new features at the time.
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, typepython3 scheme i <file.scm>
. To exit the Scheme interpreter, type(exit)
.
You may find it useful to try scheme.cs61a.org when working through problems, as it can draw environment and boxandpointer diagrams and it lets you walk your code stepbystep (similar to Python Tutor). Don't forget to submit your code through Ok though!
Control Structures
If Expressions
Let's introduce control expressions to allow our procedures to do more complex operations! The ifexpression has the following format:
(if <condition>
<true_result>
<false_result>)
For example, the following code written in Scheme and Python are equivalent:
Scheme  Python 



In Scheme, you cannot write elif
cases. If you want to have multiple cases with the ifexpression, you would need multiple branched ifexpressions:
Scheme  Python 



Cond Expressions
Using nested ifexpressions doesn't seem like a very practical way to take care of multiple cases. Instead, we can use the cond
special form, a general conditional expression similar to a multiclause conditional expression in Python.
(cond
(<p1> <e1>)
(<p2> <e2>)
...
(<pn> <en>)
(else <elseexpression>))
It consists of the symbol cond
followed by pairs of expressions enclosed in parentheses (<p> <e>)
called clauses. The first expression in each pair is a predicate: an expression whose value is interpreted as either True
or False
. The second expression is the return expression corresponding to its predicate.
The following code is equivalent:
Scheme  Python 



Lists
Scheme Pairs
Scheme lists are very similar to the linked lists we've been working with in
Python. Scheme lists are made up of pairs, which can point to two objects. To
create a pair, we use the cons
procedure, which takes in two arguments:
scm> (define a (cons 3 5))
a
scm> a
(3 . 5)
We can use the car
and cdr
procedures to retrieve the first and second
elements in the pair, respectively.
scm> (car a)
3
scm> (cdr a)
5
Just like linked lists in Python, lists in Scheme are formed by having the
first element of a pair be the first element of the list, and the second
element of the pair point to another pair containing the rest of the list. The
second element of a pair can be nil
to signify the end of the list. For
example, the sequence (1 2 3)
can be represented in Scheme with the following
line:
scm> (cons 1 (cons 2 (cons 3 nil)))
which creates the following object in Scheme:
We can then of course retrieve values from our list with the car
and cdr
procedures. (Curious about where these weird names come from?
Check out their etymology.)
scm> a
(1 2 3)
scm> (car a)
1
scm> (cdr a)
(2 3)
scm> (car (cdr (cdr a)))
3
list
There are a few other ways to create lists. We can pass a sequence of
arguments into the list
procedure, which quickly constructs a wellformed list
(one in which the cdr
of every pair is either another pair or nil
):
scm> (list 1 2 3)
(1 2 3)
Quote Form
We can also use the quote form to create a list, which performs much the same
functionality as the list
procedure. Unlike list
, we can use the quote
form to construct a malformed list. Notice that we can use a dot to separate
the car
and the cdr
of a pair, but Scheme will only show us the dot if the
list is malformed:
scm> '(1 2 3)
(1 2 3)
scm> '(1 . (2 . (3)))
(1 2 3)
scm> '(1 . (2 . 3))
(1 2 . 3)
BuiltIn Procedures for Lists
There are a few other builtin procedures in Scheme that are used for lists. Try them out!
scm> (null? nil)
______True
scm> (append '(1 2 3) '(4 5 6))
______(1 2 3 4 5 6)
scm> (cons '(1 2 3) '(4 5 6))
______((1 2 3) 4 5 6)
scm> (list '(1 2 3) '(4 5 6))
______((1 2 3) (4 5 6))
scm> (length '(1 2 3 4 5))
______5
Lambdas
Ah yes, you thought you were safe, but we can also write lambda
procedures in Scheme!
As noted above, the syntax for defining a procedure in Scheme is:
(define (<name> <params>)
<body>
)
Defining a lambda
has a slightly different syntax, as follows:
(lambda (<params>)
<body>
)
Notice how the only difference is the lack of procedure name. You can create and call a lambda procedure in Scheme as follows:
; defining a lambda
(lambda (x) (+ x 3))
; calling a lambda
((lambda (x) (+ x 3)) 7)
Required Questions
What Would Scheme Display?
Q1: WWSD: Lists
Use Ok to test your knowledge with the following "What Would Scheme Display?" questions:
python3 ok q wwsplists u
scm> (cons 1 2)
______(1 . 2)
scm> (cons 1 (cons 2 nil))
______(1 2)
scm> (car (cons 1 (cons 2 nil)))
______1
scm> (cdr (cons 1 (cons 2 nil)))
______(2)
scm> (list 1 2 3)
______(1 2 3)
scm> (list 1 (cons 2 3))
______(1 (2 . 3))
scm> '(1 2 3)
______(1 2 3)
scm> '(2 . 3)
______(2 . 3)
scm> '(2 . (3)) ; Recall dot notation rule
______(2 3)
scm> (equal? '(1 . (2 . 3)) (cons 1 (cons 2 (cons 3 nil))))
______False
scm> (equal? '(1 . (2 . 3)) (cons 1 (cons 2 3)))
______True
scm> (equal? '(1 . (2 . 3)) (list 1 (cons 2 3)))
______False
scm> (cons 1 '(list 2 3)) ; Recall quoting
______(1 list 2 3)
scm> (cons (list 2 (cons 3 4)) nil)
______((2 (3 . 4)))
scm> (car (cdr '(127 . ((131 . (137))))))
______(131 137)
scm> (equal? '(1 . ((2 . 3))) (cons 1 (cons (cons 2 3) nil)))
______True
scm> '(cons 4 (cons (cons 6 8) ()))
______(cons 4 (cons (cons 6 8) ()))
Coding Questions
Q2: Over or Under
Define a procedure overorunder
which takes in an x
and a y
and
returns the the following:
 return 1 if
x
is less thany
 return 0 if
x
is equal toy
 return 1 if
x
is greater thany
(define (overorunder x y)
'YOURCODEHERE
(cond
((< x y) 1)
((= x y) 0)
(else 1)))
;;; Tests
(overorunder 1 2)
; expect 1
(overorunder 2 1)
; expect 1
(overorunder 1 1)
; expect 0
Use Ok to unlock and test your code:
python3 ok q overorunder u
python3 ok q overorunder
Q3: Filter
Write a procedure filter
, which takes a predicate f
and a list lst
, and
returns a new list containing only elements of the list that satisfy the
predicate.
(define (filter f lst)
'YOURCODEHERE
(cond ((null? lst) '())
((f (car lst)) (cons (car lst) (filter f (cdr lst))))
(else (filter f (cdr lst)))))
;;; Tests
(define (even? x)
(= (modulo x 2) 0))
(filter even? '(0 1 1 2 3 5 8))
; expect (0 2 8)
Use Ok to unlock and test your code:
python3 ok q filter u
python3 ok q filter
Q4: Make Adder
Write the procedure makeadder
which takes in an initial number,
num
, and then returns a procedure. This returned procedure takes in a
number x
and returns the result of x + num
.
(define (makeadder num)
'YOURCODEHERE
(lambda (x) (+ x num)))
;;; Tests
(define adder (makeadder 5))
(adder 8)
; expect 13
Use Ok to unlock and test your code:
python3 ok q makeadder u
python3 ok q makeadder
Optional Questions
The following questions are for extra practice  they can be found in the the lab09_extra.scm file. It is recommended that you complete these problems on your own time.
Q5: Make a List
Create the list with the following boxandpointer diagram:
(define lst
'YOURCODEHERE
(cons (cons 1 '())
(cons 2
(cons (cons 3 4)
(cons 5 '())))))
Use Ok to unlock and test your code:
python3 ok q makelist u
python3 ok q makelist
Q6: Compose
Write the procedure composed
, which takes in procedures f
and g
and outputs a new procedure. This new procedure takes in a number x
and outputs the result of calling f
on g
of x
.
(define (composed f g)
'YOURCODEHERE
(lambda (x) (f (g x))))
Use Ok to unlock and test your code:
python3 ok q composed u
python3 ok q composed
Q7: Remove
Implement a procedure remove
that takes in a list and returns a new list with
all instances of item
removed from lst
. You may assume the list will only
consist of numbers and will not have nested lists.
Hint: You might find the filter
procedure useful.
(define (remove item lst)
'YOURCODEHERE
(cond ((null? lst) '())
((equal? item (car lst)) (remove item (cdr lst)))
(else (cons (car lst) (remove item (cdr lst))))))
(define (remove item lst)
(filter (lambda (x) (not (= x item))) lst))
;;; Tests
(remove 3 nil)
; expect ()
(remove 3 '(1 3 5))
; expect (1 5)
(remove 5 '(5 3 5 5 1 4 5 4))
; expect (3 1 4 4)
Use Ok to unlock and test your code:
python3 ok q remove u
python3 ok q remove
Q8: Greatest Common Divisor
Let's revisit a familiar problem: finding the greatest common divisor of two numbers.
Write the procedure gcd
, which computes the gcd of numbers a
and b
.
Recall that the greatest common divisor of two positive integers a
and b
is the largest integer which evenly divides both numbers (with no remainder).
Euclid's
algorithm states
that the greatest common divisor is
 the smaller value if it evenly divides the larger value, OR
 the greatest common divisor of the smaller value and the remainder of the larger value divided by the smaller value
In other words, if a
is greater than b
and a
is not divisible by
b
, then
gcd(a, b) == gcd(b, a % b)
You may find the provided procedures min
and max
helpful. You can
also use the builtin modulo
procedure.
(define (max a b) (if (> a b) a b))
(define (min a b) (if (> a b) b a))
(define (gcd a b)
'YOURCODEHERE
(cond ((zero? a) b)
((zero? b) a)
((= (modulo (max a b) (min a b)) 0) (min a b))
(else (gcd (min a b) (modulo (max a b) (min a b))))))
;;; Tests
(gcd 24 60)
; expect 12
(gcd 1071 462)
; expect 21
Use Ok to unlock and test your code:
python3 ok q gcd u
python3 ok q gcd
Q9: No Repeats
Implement norepeats
, which takes a list of numbers s
as input and returns
a list that has all of the unique elements of s
in the order that they first
appear, but no repeats. For example, (norepeats (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
procedure.
(define (norepeats s)
'YOURCODEHERE
(if (null? s) s
(cons (car s)
(norepeats (filter (lambda (x) (not (= (car s) x))) (cdr s))))))
Use Ok to unlock and test your code:
python3 ok q norepeats u
python3 ok q norepeats
Q10: Substitute
Write a procedure substitute
that takes three arguments: a list s
, an old
word, and a new
word. It returns a list with the elements of s
, but with
every occurrence of old
replaced by new
, even within sublists.
Hint: The builtin pair?
predicate returns True if its argument is a cons
pair.
Hint: The =
operator will only let you compare numbers, but using equal?
or eq?
will let you compare symbols as well as numbers. For more information,
check out the
Scheme Primitives Reference.
Use Ok to unlock and test your code:
python3 ok q substitute u
python3 ok q substitute
(define (substitute s old new)
'YOURCODEHERE
(cond ((null? s) nil)
((pair? (car s)) (cons (substitute (car s) old new)
(substitute (cdr s) old new)))
((equal? (car s) old) (cons new
(substitute (cdr s) old new)))
(else (cons (car s) (substitute (cdr s) old new)))))
Remember that we want to use equal?
to compare symbols since =
will only
work for numbers!
If the input list is empty, there's nothing to substitute. That's a pretty straightforward base case. Otherwise, our list has at least one item.
We can break the rest of this problem into roughly two big cases:
Nested list here
This means that (car s)
is a pair. Since you can assume that the list is
wellformed, (list? (car s))
is also an adequate check. In this case, we have
to dig deeper and recurse on (car s)
since there could be symbols to replace
in there. We must recurse on (cdr s)
as well to handle the rest of the list.
No nested list here
This is the case if (car s)
is not a pair. Of course, there could still be
nesting later on in the list, but we'll rely on our recursive call to handle
that.
If (car s)
matches old
, we'll make sure to use new
in its place.
Otherwise, we'll use (car s)
without replacing it. In both cases, we must
recurse on the rest of the list.
Video walkthrough: https://youtu.be/LAr_twxXao
Q11: Sub All
Write suball
, which takes a list s
, a list of old
words, and a
list of new
words; the last two lists must be the same length. It returns a
list with the elements of s
, but with each word that occurs in the second
argument replaced by the corresponding word of the third argument. You may use
substitute
in your solution.
(define (suball s olds news)
'YOURCODEHERE
(if (null? olds)
s
(suball (substitute s (car olds) (car news))
(cdr olds)
(cdr news))))
Solving suball
means just repeatedly doing the substitute operation we wrote
earlier. If this were Python, we might iterate over the list of olds and news,
calling substitute
and saving the result for the next call. For example, it
might look something like this:
def sub_all(s, olds, news):
for o, n in zip(olds, news):
s = substitute(s, o, n)
return s
If that approach makes sense, then the only tricky part now is to translate that
logic into Scheme. Since we don't have access to iteration, we have to reflect
our progress in our recursive call to suball
. This means shortening the list
of olds
and news
, and most importantly, feeding the result of substitute
into the next call.
Therefore, the base case is if we have nothing we want to replace in olds
.
Checking if news
is empty would also be ok, since olds
and news
should be
the same length.
What doesn't work, however, is checking if s
is an empty list. While this
won't make your solution wrong on its own, it's an insufficient base case.
Remember that we're passing in s
with elements replaced into the recursive
call, which means it won't become any shorter.
Video walkthrough: https://youtu.be/avYPLlaBtj0
Use Ok to unlock and test your code:
python3 ok q suball u
python3 ok q suball