99道习题来自 http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html,并且该网页上有解答。
P01 (*) Find the last box of a list. (查找列表最后一个元素)
* (my-last '(a b c d))
(D)
(defun my-last (lst)
(if (null (cdr lst)) ;(cdr nil) equal nil
lst
(my-last (cdr lst))))
(defun my-last-1 (lst)
(if (null lst)
nil
(let ((len (length lst)))
(nthcdr (- len 1) lst))))
* (my-but-last '(a b c d))
(C D)
(defun my-but-last (lst)
(let ((len (length lst)))
(if (> len 1)
(subseq lst (- (length lst) 2))
nil)))
(defun my-but-last-1 (lst)
(if (null (cddr lst))
lst
(my-but-last-1 (cdr lst))))
网页上有新的解法
Example:
* (element-at '(a b c d e) 3)
C
(defun element-at (lst n)
(cond ((null lst) nil)
((= n 1) (car lst))
(t (element-at (cdr lst) (- n 1)))))
P04 (*) Find the number of elements of a list.
(defun lenght-lst (lst)
(if (null lst)
0
(1+ (lenght-lst (cdr lst)))))
P05 (*) Reverse a list.
(defun reverse-lst (lst)
(if (null lst)
nil
(nconc (reverse-lst (cdr lst)) (list (car lst)))))
(defun reverse-lst-1 (lst)
(labels ((rec (lst acc)
(if (null lst)
acc
(rec (cdr lst) (cons (car lst) acc)))))
(rec lst nil)))
P06 (*) Find out whether a list is a palindrome.
链表是否中心对称,将链表逆转,然后查看链表是否一样
(defun palindrome (lst)
(let ((lst1 (reverse-lst-1 lst)))
(labels ((rec (lst lst1)
(if (null lst)
t
(and (equal (car lst) (car lst1))
(rec (cdr lst) (cdr lst1))))))
(rec lst lst1))))
(defun palindrome-1 (lst)
(let ((lst1 (reverse-lst-1 lst)))
(equal lst lst1)))
Example:
* (my-flatten '(a (b (c d) e)))
(A B C D E)
(defun my-flatten (tree)
(cond ((null tree) nil)
((atom tree) (list tree))
(t (nconc (my-flatten (car tree))
(my-flatten (cdr tree))))))
P08 (**) Eliminate consecutive duplicates of list elements.