4

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

Óscar López
  • 232,561
  • 37
  • 312
  • 386
deltanovember
  • 42,611
  • 64
  • 162
  • 244

5 Answers5

10

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))))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
6
(defn palindrome? [num]
  (= (seq (str num)) (clojure.string/reverse (str num))))
swcai
  • 675
  • 5
  • 12
  • 1
    reverse is linear time for a seq. It's better to use clojure.string/reverse to reverse the String. If you already have a vector, rseq is constant time for a vector. – miner49r Feb 21 '12 at 19:54
3

Your code returns false because it is comparing a string with a sequence, which can never be equal.

You can make it work by explicitly converting the string into a seq as follows:

(defn is-palindrome? [num] 
  (let [digit-sequence (seq (str num))]
    (= digit-sequence (reverse digit-sequence))))
mikera
  • 105,238
  • 25
  • 256
  • 415
1

It turns out the the overhead of manipulating collections of characters dominates, so it's actually faster to compare the original string to a reversed version even though it seems like you're comparing twice as many characters as necessary. Make sure you use clojure.string/reverse, not clojure.core/reverse. The usual Clojure convention is to end a predicate with a question mark, but not to use the "is" prefix.

(require 'clojure.string)

(defn palindrome? [s] (= s (clojure.string/reverse s)))
(defn palindrome-num? [n] (palindrome? (str n)))
miner49r
  • 1,087
  • 1
  • 14
  • 10
0
(reverse (str 1221))

returns a List of characters

(\1 \2 \2 \1)

but (str 1221) is a java String

Sathish
  • 20,660
  • 24
  • 63
  • 71