Solutions to exercises from "lecture notes 5"

(defun dolist-adder (list)
  (let* ((total 0))
    (dolist (number list)
      (incf total number))

(defun dotimes-factorial (number)
  (let* ((factorial 1))
    (dotimes (i number)
      (setf factorial (* factorial (1+ i))))

(defun recursive-length (list)
  (if list
      (1+ (recursive-length (cdr list)))

(defun recursive-copy-list (list)
  (if list
      (cons (car list)
            (recursive-copy-list (cdr list)))))

(defun recursive-reverse (list &optional reverse)
  (if list
      (recursive-reverse (cdr list)
                         (cons (car list) reverse))

(defun iterative-length (list)
  (let* ((length 0))
    (dolist (x list)
      (incf length))

(defun iterative-copy-list (list)
  (let* ((copy nil))
    (dolist (x list)
      (push x copy))
    (reverse copy)))

;; the above is close enough to (defun copy-list (list) (reverse
;; (reverse list))) that I don't like it. I suppose the following will
;; do (and is probably very close to the actual implementation), but
;; it's fairly revolting for beginners...

(defun iterative-copy-list (list)
  (if list
      (let* ((stub (cons nil nil))
             (last stub))
        (dolist (x list)
          (setf (cdr last) (cons x nil)
                last (cdr last)))
        (cdr stub))))

(defun mapcar-type-of (list)
  (mapcar 'type-of list))

(defun dolist-type-of (list)
  (let* ((new-list nil))
    (dolist (thing list)
      (push (type-of thing) new-list))
    (reverse new-list)))

(defun dotty (list)
  (mapc 'print-one-dot list))

(defun print-one-dot (thing)
  (format t "."))

;;; The "make sure you understand it" examples

(defun sum-two-numbers (x y)
  (+ x y))

(defun sum-first-two-members-of-list (some-list)
  (+ (first some-list)
     (second some-list)))

(defun sum-all-members-of-list (some-list)
  (dolist-adder some-list)) ; see above

(defun filter-for-negative (some-list)
  (let* ((filtered-list nil))
    (dolist (number some-list)
      (when (minusp number)
        (push number filtered-list)))
    (reverse filtered-list)))

 If you have tried the exercises, looked at the solutions and still do not understand what's going on, I am available for consultation at the times advertised on my office door. Bring your code with you in BOTH the following forms:


Nick Levine
                                                                               last modified 2000-11-01
                                                         Copyright (C) Nick Levine 1999. All rights reserved.
$Id: // $