> Greetings, Clojure community. I've been playing around with > clojure, > and just downloaded 1.3.0. Here's a REPL session, wherein I define > a power-of-two function, and apply it a couple of times. > > lecturer-01:clojure-1.3.0 kangas$ java -cp clojure-1.3.0.jar > clojure.main > Clojure 1.3.0 > user=> (defn pow2 [n] > (loop [n n, p 1] > (if (zero? n) > p > (recur (dec n) (+ p p)) ))) > #'user/pow2 > user=> (pow2 62) > 4611686018427387904 > user=> (pow2 63) > ArithmeticException integer overflow > clojure.lang.Numbers.throwIntOverflow (Numbers.java:1374) > user=> > > Previous versions would silently, automagically convert to bignums > and > give me the answer I wanted. Is clojure-1.3.0 too serious, > enterprisy, and > Java-like for this sort of thing? I found no clue in the list of > changes.
This has to do with the primitive math support in Clojure 1.3. Every number is now a primitive unless otherwise mentioned. `(pow2 63)` is throwing an exception now because 63 is a primitive int. If you want `pow2` to work well on large numbers you will have to use the arbitrary precision math functions like +', -', *', /', etc. You can also take advantage of BigInteger contagion by switching the initial value of p to 1N instead of 1. Thus you can write your function in two ways - ;;; Use arbitrary precision add function. Will return BigInteger when needed. (defn pow2 [n] (loop [n n, p 1] (if (zero? n) p (recur (dec n) (+' p p))))) ; +' instead of + ;;; Utilize BigInteger contagion. Will always return BigInteger. (defn pow2 [n] (loop [n n, p 1N] ; this is different (if (zero? n) p (recur (dec n) (+ p p))))) I hope that helps. Regards, BG -- Baishampayan Ghose b.ghose at gmail.com -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en