LISP - recursive palindrome

I am trying to write a recursive palindrome function. The code works using two functions like this: (set str

(abcd))

(defun reverseString (l)
    (cond
        ( (null l) nil)
            (T (append (reverseString (cdr l)) (list (car l))))
    )
)

(defun palindrome (l)
    (cond
        ( (null l) nil)
             (T (append l(reverseString (cdr l)) (list (car l))))
    )
)

      

However, I am trying to combine it into one function:

(defun palindrome (l)
    (cond
        ( (null l)
                nil
        )
        (T 
            (append str(append (palindrome (cdr l)) (list (car l))) )
        )
    )
)

      

This returns (ABCDABCDABCDABCDDCBA)

Where I want it to return (abcddcba) and then (abcdcba) ** not repeat the last character when it changes direction.

I know there are easier ways to do this with predefined functions, but I'm trying to challenge myself a bit. However I am stuck here and it will be very helpful for us to help.

+3


source to share


1 answer


Here is a recursive palindrome of one function:

(defun palindrome(l)
  (cond ((null l) nil)
        (t (append (list (car l)) (palindrome (cdr l)) (list (car l))))))

      

The recursion is structured like this: make the rest of the list palindrome and place the first element of the list at the beginning and end.



If you only want to have the centerpiece once, here's an alternative version:

(defun palindrome(l)
  (cond ((null l) nil)
        ((null (cdr l)) (list (car l)))
        (t (append (list (car l)) (palindrome (cdr l)) (list (car l))))))

      

that is, you have to add a new case to terminate the recursive function: termination also when there is only one element, and return that element.

+3


source







All Articles