From: John Gilson
Subject: Re: Cons Cells
Date: 
Message-ID: <ZG4F9.166525$gB.35247054@twister.nyc.rr.com>
"A.Melon" <·····@melontraffickers.com> wrote in message
·····································@melontraffickers.com...
> How can I create a function in Lisp to count the number of cons cells that a list is using? For
> example, (num-cons-cells '(1 2 (3 (4 5)) 6)) => 8.
>
> Also, how can I create another function to create an associative list mapping a symbol to the
number
> of times it occurs. For example, (map '(a)) => ((a . 1))
>
> Thank you
> Jane

(defun num-cons-cells (object)
   (if (consp object)
         (+ 1 (num-cons-cells (first object)) (num-cons-cells (rest object)))
         0))

(defun occurrences (list &key (test #'eql))
    (if (consp list)
         (let (alist)
            (labels ((occurrences-aux (object)
                           (cond ((null object))
                                      ((consp object)
                                       (occurrences-aux (first object))
                                       (occurrences-aux (rest object)))
                                      (t
                                       (let ((count (assoc object alist :test test)))
                                          (if (null count)
                                               (setf alist (acons object 1 alist))
                                               (incf (rest count))))))))
              (occurrences-aux (first list))
              (occurrences-aux (rest list)))
           alist)))

Regards,
jag