POSTS

Lisp problem solved

Blog

There are many ways do skin a cat, but here’s how I handled the occurrences task…

Answer

>(occurrences '(a b a d a c d c a))
((A . 4) (C . 2) (D . 2) (B . 1))

See, it retuns the token (A, B, etc.) and how many times it occurred

Code

(defun occurrences (queue)
  (sort-count-pairs (scan-queue queue () () )
))

(defun scan-queue (aQueue aSearched aCount)
  (if (null (car aQueue))
      aCount
      (progn
	(if (member (car aQueue) aSearched)
	    (scan-queue (cdr aQueue) aSearched aCount)
	    (let ((scantoken (car aQueue)))
	      (push scantoken aSearched)
	      (push
	       (count-token scantoken aQueue  0)
	       aCount)
	      (scan-queue (cdr aQueue) aSearched aCount))))))

(defun count-token (sToken aQ count)
  (if (null (car aQ))
	(cons count sToken)
      (progn
	(if (equal (car aQ) sToken )
	    (setf count (+ count 1)))
	(count-token sToken (cdr aQ) count))))

(defun sort-count-pairs (pairs)
  (let ((sortcount
	 (mapcar #'(lambda (x) (car x)) pairs)))
    (sort sortcount #'>)
    (mapcar #'(lambda (x)
		(let ((mypair (assoc x pairs)))
		  (setf pairs (remove (assoc x pairs) pairs))
		  (cons (cdr mypair) (car mypair)))) sortcount)))