October 2, 1995
Due in quiz sections October 17, 1995
twice that takes a
list of atoms (which may be empty), and returns a new list of the same
length, where each element in the new list is a list of length two, with
the original element repeated. Examples:
(defun twice (x)
(if (null x) nil
(cons (list (first x) (first x))
(twice (rest x)))))
twice, which should use one of
the applicative operators instead. This version should not be recursive.
(defun twice (x) (mapcar #'(lambda (a) (list a a)) x))
twice
function, called flat-twice, that takes a
list of atoms (which may be empty), and returns a new list with each atom
repeated. You can use either recursion or applicative programming (but no
side effects). Examples:
;;; using recursion
(defun flat-twice (x) (if (null x) nil
(let ((head (first x)))
(cons head (cons head (flat-twice (rest x)))))))
;;; using applicative programming
(defun flat-twice (x) (reduce #'append (twice x)))
boolean-eval that takes a
list, which should be a boolean expression, and returns its value.
Don't use the built-in function eval in writing
boolean-eval (which would result in a one-line solution!) --
the idea is to write your own evaluation function for booleans. Hint: this
function should be multiple recursive. We can define a boolean expression
as one of the following:
t
nil
(and <boolean-expression>
<boolean-expression>)
(or <boolean-expression>
<boolean-expression>)
(not <boolean-expression>)
;;; note that in this solution we assume the following that we will
;;; get input that fits the above template for boolean expressions.
;;; and if we can detect that the input does not fit we call it 't'
;;; in the style of lisp.
(defun boolean-eval (x)
(cond ((null x) nil) ;nil atom is nil
((atom x) t) ;any other atom is t
((equal (first x) 'and) ;use built in function 'and' on
;the results of recursive calls to
;the second and third arguments
(and (boolean-eval (second x)) (boolean-eval (third x))))
((equal (first x) 'or) ;use built in function 'or' on
;the results of recursive calls to
;the second and third arguments
(or (boolean-eval (second x)) (boolean-eval (third x))))
((equal (first x) 'not) ;use built in function 'not' on
;the result of a recursive call to
;the second argument
(not (boolean-eval (second x))))
(t t))) ;anything else is considered t