Practice Problems

Inserting a Number into an Sorted List

Write a recursive function (insert n lon), where n is a number and lon is a list of of numbers in increasing order. Recall that the BNF definition of a list of numbers is:
<list-of-numbers> ::= ()
                    | (<number> . <list-of-numbers>)
insert returns a lon consisting of n and all of the elements of lon, still in increasing order. For example:
> (insert 3 '(1 2 4))
(1 2 3 4)

> (insert 100 '())
(100)

> (insert 0 '(1 2 4))
(0 1 2 4)

Finding an Item in an s-list

Write a mutually recursive function (slist-contains? s slst) that takes two arguments, a symbol ss and an s-list slst:
           <s-list> ::= ()
                      | (<symbol-expression> . <s-list>)

<symbol-expression> ::= <symbol> 
                      | <s-list>
slist-contains? returns true if s appears anywhere in slst, and false otherwise. For example:
> (slist-contains? 'eugene '((a b) (((b g r) (f r)) c (d e)) b))
#f

> (slist-contains? '/ '(if (zero? n) zero (/ total n)))
#t
slist-contains? must be mutually recursive with the function symexp-contains?, which determines if a symbol appears anywhere in a symbol expression.

Applying Function Based on List Position

Write a structurally recursive function (apply-by-position f lon).

apply-by-position takes two arguments, a two-argument function (f item position) and a list of numbers lon:
<list-of-numbers> ::= ()
                    | (<number> . <list-of-numbers>)
apply-by-position returns a list of numbers consisting of the values returned by f when applied to each number and its zero-based position in lon. For example:
> (apply-by-position * '(3 2 -4))
'(0 2 -8)      ; each item multiplied by its position

> (apply-by-position expt '(3 2 -4))
'(1 2 16)      ; each item raised to the power of its position
You'll need an interface procedure here, so that each recursive call can know the position of the current item.

Is a Variable Used in an Expression?

Write a structurally recursive function (contains-varref? v exp) that takes two arguments: v, a symbol, and exp, an expression in our little language:
<exp> ::= <varref>
        | (lambda (<var>) <exp>)
        | (<exp> <exp>)
contains-varref? returns true if v is used as a variable reference anywhere in exp, and false otherwise. For example:
> (contains-varref? 'y 'y)
#t
> (contains-varref? 'x '(lambda (x) x))
#t
> (contains-varref? 'y '(lambda (y) x))
#f
> (contains-varref? 'x '(f (lambda (y) x)))
#t
> (contains-varref? 'x '( (lambda (x) y)      ; x is not used here
                          (lambda (y) x) ))   ; but x is used here
#t
You must use these syntax procedures for the little language, as provided in class.
exp?
varref?
lambda?   lambda->param  lambda->body
app?      app->proc      app->arg