4

I've been playing with Clojure lately and I can't get this algorithm to work:

(defn reverse-number [number reversed]
   (if (= number 0)
     reversed
     (reverse-number (/ number 10) 
                     (+ (rem number 10) (* reversed 10)))))

This is how I should call it (reverse-number 123 0) and the result I expect is: 321. When I run this, the REPL just hangs.

Can someone explain me, please, what is happening, what I did wrong and how to get this function working?

Note: I know I can use string functions to reverse a number. Actually, I already did this, but I'm not interested in this solution. All I want is to make the leap to functional languages. That's why I try multiple approaches.

Using string functions:

(defn reverse-number [n]
  (Integer. (clojure.string/reverse (str n))))

(reverse-number 123)  ; --> 321

I don't like this version since it feels like cheating by using the string version of reverse.

2
  • 1
    What would 3210 be in reverse? Commented Dec 30, 2012 at 13:44
  • @Gumbo: 123, why? This is the answer I expect. I certainly wouldn't expect 0123 since that wouldn't be a correct number... Commented Dec 30, 2012 at 17:08

1 Answer 1

5

You should use quot instead of /.

/ in clojure will give you a fraction so number will never be 0 (unless it's 0 from the beginning), while quot will give you "integer division".

Examples:

user=> (/ 123 10)                  
123/10
user=> (quot 123 10)
12
Sign up to request clarification or add additional context in comments.

1 Comment

+1 - I was just about to ask how Clojure implemented truncating division.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.