some simple recursive lisp programs
May 9, 2014
- Write a procedure count-list to count the number of elements in a list
(defun count-list (numbers)
(if (null numbers) 0
(+ 1 (count-list (rest numbers)))))
(print (count-list '(1 2 3)))
result: 3
- Write a procedure reverse-list to reverse each word in a list of words
(defun reverse-list (numbers)
(if (null numbers) nil
(cons (reverse (first numbers)) (reverse-list (rest numbers)))))
(reverse-list '("dog" "pan" "tar" "tip" "net"))
result: ("god" "nap" "rat" "pit" "ten")
- Write a procedure evenp-list to process a list of numbers, replacing each number by t if it’s even, and nil if it’s odd
(defun evenp-list (numbers)
(if (null numbers) nil
(cons (if (evenp (first numbers)) t nil)
(evenp-list (rest numbers)))))
(evenp-list '(1 2 3 4 5 6 7 8))
result:
(nil t nil t nil t nil t)
- Write a procedure max-list to return the maximum element of a list.
(defun max-list (numbers)
(if (null numbers) 0
(if (> (first numbers) (max-list (rest numbers)))
(first numbers)
(max-list (rest numbers)))))
(max-list '(11 13 17 19 2 3 5 7))
should return 19.
These three small programs are all recursive. It is interesting to code in lisp. ;)
The fourth program is incorrect. There is bug: I assume that all numbers in the list are positive.
The following program is better:
(defun max-list (numbers)
(if (null (rest numbers)) (first numbers)
(if (> (first numbers) (max-list (rest numbers)))
(first numbers)
(max-list (rest numbers)))))
btw, max is a build-in procedure. so:
(defun max-list (numbers)
(if (null (rest numbers)) (first numbers)
(max (first numbers) (max-list (rest numbers))
)))
It becomes simpler. ;)