This common lisp program is an exercise to print an integer and its digits reversed to the screen.
(defun read-number () (format t "Enter a number: ~%") (read))
(defun reverse-string (the-string)
(if (eq (length the-string) 0)
""
(concatenate 'string (reverse-string (subseq the-string 1)) (subseq the-string 0 1))))
(defun reverse-digits (the-number) (reverse-string (write-to-string the-number)))
(let ((the-number (read-number)))
(format t "N->: ~a~%<-N: ~a~%" the-number (reverse-digits the-number)))
Thanks for the feedback, everyone, and thanks too for pointing out that the exercise was to reverse a number - not a string. I wrote a version of this that reverses a number using recursion and would very much like feedback on this version too. Thanks for your time!
;; Write a program to, given an integer, write the number and its digits reversed to the screen.
(defun read-number () (format t "Enter a number: ~%") (read))
(defun reverse-digits-unwrap (fifo multiplier)
(if (= multiplier 1) (car fifo)
(+ (* multiplier (car fifo)) (reverse-digits-unwrap (cdr fifo) (/ multiplier 10)))))
(defun reverse-digits (the-number &OPTIONAL fifo multiplier)
(let* ((remainder (mod the-number 10))
(next-number (/ (- the-number remainder) 10))
(fifo (if (null fifo) (list remainder) (append fifo (list remainder))))
(multiplier (if (null multiplier) 1 (* multiplier 10))))
(if (= 0 next-number)
(reverse-digits-unwrap fifo multiplier)
(reverse-digits next-number fifo multiplier))))
(let ((the-number (read-number)))
(format t "N->: ~a~%<-N: ~a~%" the-number (reverse-digits the-number)))