PasteRack.org
Paste # 70152
2017-05-22 15:03:54

Fork as a new paste.

Paste viewed 107 times.


Embed:

  1. #lang racket
  2.  
  3. ;Problem 21. Write a predicate palindrome?, which processes a list of numbers and returns a boolean indicating whether the numbers would be the same in forward and reverse order. E.g.:
  4. ;(palindrome? '())  #t
  5. ;(palindrome? '(1))  #t
  6. ;(palindrome? '(1 1))  #t
  7. ;(palindrome? '(1 2 1))  #t
  8. ;(palindrome? '(1 2 3 2 1))  #t
  9. ;(palindrome? '(1 2 3))  #f
  10. ;Assume you have the following functions available:
  11. ;last—returns the last item in a list
  12. ;butlast—return all items in the list except the last item
  13. ;Do not define / use reverse. The following is correct but will not receive credit: (define (palindrome? lst) (equal? lst (reverse lst)))
  14. ;Do not use map/filter/accumulate. Use direct recursion.
  15.  
  16. (define (palindrome? lst)
  17.   (cond
  18.     [(empty? lst) #t] ;if the list is empty its a palidrome
  19.     [(= 1 (length-i lst)) #t];if we have reached the middle of the list then the list must be a palidrome
  20.     [(not (= (car lst) (last lst))) #f];if the first element and the last element dont equal then the list is not a palidrome
  21.     [else (palindrome? (butlast (cdr lst)))])) ;remove the (car lst) and (last lst) from the list and pass it in

=>