3.23 Palindromes
A palindrome is a number that reads the same forwards and backwards, like 12321. Write a program that tests input integers for the palindrome property.
Hint: This should not be done with the numbers in their input (character) format.
For the task above, I have written the following program. Rather than converting the number to a string, I recursively divide the number to create a list of individual digits and then compare the digits from outside to in to determine if it's a palindrome. What do you think of my strategy and of my code in general? I understand that tail recursion is not guaranteed to work in Common Lisp - should I rewrite this code to use loops instead?
(defun collect-digits (candidate &OPTIONAL (digit-list ()))
; make a list out of the digits of the number
; example: (= (collect-digits 12321) (1 2 3 2 1)) is true
(if (< candidate 10)
(cons candidate digit-list)
(multiple-value-call
(lambda (sub-candidate onesdigit)
(collect-digits sub-candidate (cons onesdigit digit-list)))
(floor candidate 10))))
(defun reflection-p (candidate-list &OPTIONAL (len (length candidate-list)))
; if c-l[first] = c-l[last]
(and (= (car candidate-list) (car (last candidate-list 1)))
; and the list is 3 or smaller ex. (3 1 3), it is a reflection
(if (<= len 3) t
; if longer, keep looking
(reflection-p (subseq candidate-list 1 (1- len)) (- len 2)))))
(defun palindrome-p (candidate)
(reflection-p (collect-digits candidate)))
(format t "12321: ~a ~%3456789 ~a ~%" (palindrome-p 12321) (palindrome-p 3456789))