标签:style blog class code tar color
1. Write a procedure count-list to count the number of elements in a list
1 (defun count-list (numbers) 2 (if (null numbers) 0 3 (+ 1 (count-list (rest numbers))))) 4 (print (count-list ‘(1 2 3))) 5 6 result: 3
2. Write a procedure reverse-list to reverse each word in a list of words
1 (defun reverse-list (numbers) 2 (if (null numbers) nil 3 (cons (reverse (first numbers)) (reverse-list (rest numbers))))) 4 (reverse-list ‘("dog" "pan" "tar" "tip" "net")) 5 6 result: ("god" "nap" "rat" "pit" "ten")
3. 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
1 (defun evenp-list (numbers) 2 (if (null numbers) nil 3 (cons (if (evenp (first numbers)) t nil) 4 (evenp-list (rest numbers)))))
(evenp-list ‘(1 2 3 4 5 6 7 8))
result:
(nil t nil t nil t nil t)
4. Write a procedure max-list to return the maximum element of a list.
1 (defun max-list (numbers) 2 (if (null numbers) 0 3 (if (> (first numbers) (max-list (rest numbers))) 4 (first numbers) 5 (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:
1 (defun max-list (numbers) 2 (if (null (rest numbers)) (first numbers) 3 (if (> (first numbers) (max-list (rest numbers))) 4 (first numbers) 5 (max-list (rest numbers)))))
btw, max is a build-in procedure. so:
1 (defun max-list (numbers) 2 (if (null (rest numbers)) (first numbers) 3 (max (first numbers) (max-list (rest numbers)) 4 )))
It becomes simpler. ;)
some simple recursive lisp programs,布布扣,bubuko.com
some simple recursive lisp programs
标签:style blog class code tar color
原文地址:http://www.cnblogs.com/liuxueyang/p/3718008.html