This is a collection of blog entries written while learning Lisp. It is posted in the order written so you probably want to jump to the first post.

Wednesday, October 31, 2007

99 Lisp Problems

Ran across this website which has 99 Lisp problems, can't do them all, but I can do a few. They even include solutions to the problems so after you do it you can compare yours with theirs.

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 comment:

Kamal said...
This comment has been removed by the author.