Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure, I want Long multiplication to overflow

I want to do 64 bit arithmetics (not natural numbers), so I e.g. need a multiplication of two longs to overflow silently.

(unchecked-multiply Long/MAX_VALUE 3)

does the trick. But

(def n Long/MAX_VALUE)
(unchecked-multiply n 3)

gives an overflow exception. What am I doing wrong?

(Clojure 1.5.1)

like image 981
Falko Avatar asked Sep 09 '13 13:09

Falko


1 Answers

In the first case, both arguments are unboxed longs, so the (long, long) overload of clojure.lang.Numbers.unchecked_multiply is used. As expected, it does not throw on overflow.

In the second case, n is boxed, so the (Object, Object) overload is called, and that simply delegates to the multiply method which throws on overflow.

You need to say

(unchecked-multiply (long n) 3)

so that the (long, long) overload is used.

like image 170
Michał Marczyk Avatar answered Oct 23 '22 03:10

Michał Marczyk