Subject: Re: count symbols in a list
From: Erik Naggum <erik@naggum.no>
Date: 02 Dec 2002 08:18:47 +0000
Newsgroups: comp.lang.lisp
Message-ID: <3247805927894274@naggum.no>

* "Travis Fischer" <fisc3577@uidaho.edu>
| I want to write a function that takes a list of symbols k and and lisp
| expression l and counts the number of times each symbol in k occurs in
| the lisp expression. It should return an alist binding each symbol to its
| count.  I want to do this without flattening the list before I go through
| it looking for symbols.

  Look for two things in this code: How it is formatted, and how it does
  its work.  (The way you have formatted your code annoys people.)  Explain
  to me why this works and gives the right answer when you have ascertained
  that it does.  Explain why it is efficient in both time and space.

(defun count-member (symbols tree)
  (let* ((counts (loop for symbol in symbols collect (cons symbol 0)))
         (lists (list tree))
         (tail lists))
    (dolist (list lists)
      (dolist (element list)
        (cond ((consp element)
               (setf tail (setf (cdr tail) (list element))))
              ((member element symbols :test #'eq)
               (incf (cdr (assoc element counts :test #'eq)))))))
    counts))

-- 
Erik Naggum, Oslo, Norway

Act from reason, and failure makes you rethink and study harder.
Act from faith, and failure makes you blame someone and push harder.