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)
Incrementing Every Number in an N-list
Write a mutually recursive function
(nlist++ nlst)
that takes an n-list as an argument:
<n-list> ::= () | (<number-expression> . <n-list>) <number-expression> ::= <number> | <n-list>
nlist++
returns an n-list of the same shape as its
argument, but with every number incremented by 1. For example:
> (nlist++ '(1 (4 (9 (16 25)) 36 49) 64)) '(2 (5 (10 (17 26)) 37 50) 65) > (nlist++ '(0 1 2 3)) '(1 2 3 4)
nlist++
must be mutually recursive with the
function numexp++
, which increments the numbers in
a number-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 positionYou'll need an interface procedure here, so that each recursive call can know the position of the current item.
Is a Variable Declared?
Write a structurally recursive function
(is-declared? v exp)
.
is-declared?
takes two arguments:
v
, a symbol, and
exp
, an expression in our little language:
<exp> ::= <varref> | (lambda (<var>) <exp>) | (<exp> <exp>)
is-declared?
returns true if v
is
declared anywhere in exp
, and false otherwise.
Recall that:
-
Only a
lambda
expression can declare a variable. -
A
lambda
expression can occur anywhere that expects an expression.
> (is-declared? 'y 'y) #f > (is-declared? 'x '(lambda (x) x)) #t > (is-declared? 'x '(lambda (y) x)) #f > (is-declared? 'x '( (lambda (y) y) ; x is not declared here (lambda (x) x) )) ; but x is declared here #tYou 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