PALINDROME: (palindrome lst) should return #t if the list lst is a palindrome, a
ID: 3545542 • Letter: P
Question
PALINDROME:
(palindrome lst) should return #t if the list lst is a palindrome, and return
#f otherwise. [A 'palindrome' is something that reads the same backwards and
forwards.] That is,
(palindrome '(s t u v w x y z))
should return:
#f
(palindrome (LIST 'j 'k 'l 'm 'l 'k 'j))
should return:
#t
Both (palindrome '()) and (palindrome '(a))
should return true, etc.
(palindrome '((a b) c (d e d) c (b a)) )
The above list should result in #t; the two lists below should produce #f.
(palindrome '((a b) c (d e d) c (a b)) )
(palindrome '((y z) y) )
If multiple arguments are called return a USAGE message.
I have tried writting it but my code only produces f for all lists.
(DEFINE (reverse lst)
(DEFINE (reverse2 lst acc)
(if (null? lst)
'()
(if (list? (car lst))
(reverse2 (cdr lst) (cons (reverse (car lst)) acc))
(reverse2 (cdr lst) (cons (car lst) acc)))))
(reverse2 lst '()))
(DEFINE (palindrome lst)
(if (equal? (reverse lst) lst )
#t
#f))
Explanation / Answer
(define (reverse lst) (cond ((list? lst) (cond ((null? lst) lst) ((null? (cdr lst)) lst) (else (append (reverse (cdr lst)) (list (car lst)) )) ) ) (else lst) ) ) (define (palindrome lst) (cond ((list? lst) (cond ((null? lst) #t) ((null? (cdr lst)) #t) ( (equal? (car lst) (reverse (car (reverse (cdr lst)) ) ) ) ( palindrome ( cdr (reverse (cdr lst) ) ) ) ) (else #f) ) ) (else "pass lst") ) )
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.