Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the following Clojure not detect a palindrome?

I'm just trying to convert to a string and compare to the reverse

(defn is-palindrome? [num]
  (= (str num) (reverse (str num))))

Something like

(is-palindrome 1221)

Is returning false

like image 878
deltanovember Avatar asked Nov 30 '22 06:11

deltanovember


1 Answers

Try this instead:

(defn is-palindrome? [num]
  (= (str num) (apply str (reverse (str num)))))

In your code, the expression (reverse (str 1221)) returns the list of characters (\1 \2 \2 \1), which needs to be turned back into a string for the comparison to work. Alternatively, you could convert both numbers to character lists and perform a list comparison instead:

(defn is-palindrome? [num]
  (= (seq (str num)) (reverse (str num))))
like image 142
Óscar López Avatar answered Dec 05 '22 08:12

Óscar López