Wednesday, January 15, 2014

99 Clojure Problems – 6: Find Out Whether a List Is a Palindrome

Example:

(deftest p06-test
  (is (= true (palindrome? '(1 2 3 3 2 1))))
  (is (= false (palindrome? '(1 2 3)))))

Solution:

One definition of a palindrome is "a sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction" [Wikipedia]. The definition contains already a possible solution. To test whether a given sequence of elements is a palindrome we can compare it with the same sequence in reverse order. We can reuse the reverse function defined to solve the last problem.

Read more about this series.

1 comment:

Seb said...

I'm breaking my head trying to come up with an "effective" solution. By "effective" I mean not doing more steps than necessary.

But I agree that the most straightforward and elegant solution is to compare the original list with its reverse.