Monday, April 5, 2010

SICP Series-chapter 2.2.1

List is one of the most important concepts in the LISP. There are already lots of function for manipulating the list in Lisp. But in the Schema, it only provides the most basic functions, like car, cdr. This textbook is based on the Schema, so there would be some exercises that are already implemented in the Common Lisp.
2.17
(defun last-pair(list)
    (if (null (cdr list))
        list
        (last-pair (cdr list))))
2.18
(defun jd-reverse(list)
    (if (null list)
        nil
        (append (jd-reverse (cdr list)) (list (car list)))))
2.20
(defun same-parity(item &rest others)
    (let ((temp (list item)))
        (dolist (other others)
            (if (= (rem item 2) (rem other 2))
                (setf temp (append temp (list other)))))
   temp))
2.21
In Common Lisp, there are a lot of mapping function.

(defun square-list(items)
    (if (null items)
        nil
        (cons (expt (car items) 2)
              (square-list (cdr items)))))
(mapcar #'square (list 1 2 3 4 5))
2.22
(defun for-each(f items)
    (dolist (item items)
        (funcall f item)))

No comments:

Post a Comment