Ninety-Nine_Lisp_Problems
So here are my solutions to the first six.
1) Find the last box of a list.
(defun my-last (lst)
(if (not (listp lst))
nil
(if (consp (cdr lst))
(my-last (cdr lst))
(car lst))))
2) Find the last but one box of a list.
(defun my-but-last (lst)
(if (not (listp lst))
nil
(if (equal 2 (list-length (cdr lst)))
(cdr lst)
(my-but-last (cdr lst)))))
3) Find the K'th element of a list.
(defun element-at (lst num)
(if (null lst)
nil
(if (eql 1 num)
(car lst)
(element-at (cdr lst) (- num 1)))))
4) Find the number of elements of a list.
(defun my-length (lst)
(if (null lst)
0
(+ 1 (my-length (cdr lst)))))
5) Reverse a list.
(defun my-reverse (lst)
(if (not (consp (cdr lst)))
(append (cdr lst) (cons (car lst) ()))
(append (my-reverse (cdr lst)) (cons (car lst) ()))))
6) Find out whether a list is a palindrome.
;; At first I had a big complicated way and then I realized...
(defun palindromep (lst)
(equal (reverse lst) lst))



1 comments:
Post a Comment