Solutions to 655 homework on list notation
1.
a. (4)
b. ((3) 4)
c. (3 (4) 5)
d. This cannot be written using the list notation since it ends with
5, not nil.
2.
a. (7 . nil)
b. (7 . (8 . nil))
c. (7 . ((8 . nil) . nil))
d. ((7 . nil) . (8 . nil))
3.
[Note that these are not Lisp/Scheme programs/expressions; Scheme
expressions don't include square brackets etc. Instead, the purpose of
this question was to make sure that you understand how the Lisp
primitives work, thinking of them as mathematical functions. If you
treated these as Scheme programs, and said that some of them will give
errors because no values were bound to some variables etc., the grader
will grade your assignment with that interpretation - that these are
Scheme programs.]
a. nil
b. 4
c. ((a) . (b))
That can also be written as ((a) b) [but not as ((a) (b))].
d. #t
4. check[ x, list ] =
[ null?[list] --> 0;
| eq?[ x, car[list] ] --> +[ 1, check[ x, cdr[list] ]];
| #t --> check[ x, cdr[list] ];
]
This works as follows: The base case is when list is empty; in that
case, x doesn't appear in the list, so return 0.
If x is equal to car[list], that should be counted, so we apply check
to x and cdr[list], add 1 to that result, and return that. If x is not
equal to car[list], this does not contribute to the count, so we just
apply check to x and cdr[list] and return that result.
As a Scheme definition:
(define (check x list)
(cond
( (null? list) 0 )
( (eq? x (car list)) (+ 1 (check x (cdr list))) )
( #t (check x (cdr list)) )
)
)
------------
A note about Lisp/Scheme implementations: Someone asked the following question:
If you try
(cons '(3) '(4))
on scheme48, it prints out
'((3) 4)
not
'((3) . (4))
as you would expect it to. How come? The answer is that, in fact,
((3) 4)
is the same as
((3) . (4))
Both are the same as:
((3 . nil) . (4 . nil))
scheme48 prefers to use the list notation when it can so it outputs
this as
((3) 4)
rather than
((3) . (4))
or
((3 . nil) . (4 . nil))