lisp 習題 occurrences

babyyellow發表於2012-08-07
  1. 定義一個函式,接受一個列表並返回一個列表,指出相等元素出現的次數,並由最常見至最少見的排序:
> (occurrences '(a b a d a c d c a))
((A . 4) (C . 2) (D . 2) (B . 1))

(defun cnt-item (item lst)
       (let (( cnt 0))
         (dolist (obj lst)
           (if (equal obj item)
           (setf cnt (+ cnt 1))))
         (cons item cnt)))

CL-USER> (cnt-item 'a '(a b c a))
(A . 2)

CL-USER> (defun occ (lst)
       (if (null lst)
           nil
           (let ((x nil))
         (dolist (obj lst)
           (pushnew (cnt-item obj lst) x  ))x)))
STYLE-WARNING: redefining COMMON-LISP-USER::OCC in DEFUN
OCC
CL-USER> (occ '(a b b a c))
((C . 1) (A . 2) (B . 2) (B . 2) (A . 2))


CL-USER> (defun occ (lst)
       (if (null lst)
           nil
           (let ((x nil))
         (dolist (obj lst)
           (pushnew (cnt-item obj lst) x :test #'equal ))x)))
STYLE-WARNING: redefining COMMON-LISP-USER::OCC in DEFUN
OCC
CL-USER> (occ '(a b b a c))
((C . 1) (B . 2) (A . 2))
CL-USER>
CL-USER> (occ '(a a  b  b  c c (a.c) b b a c))
(((A.C) . 1) (C . 3) (B . 4) (A . 3))
CL-USER>



 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/133735/viewspace-740280/,如需轉載,請註明出處,否則將追究法律責任。

相關文章