Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are those math functions end with apostrophe in Clojure?

There are some math functions that end with apostrophe like: +', *', and -'.

What is the difference between non-apostrophe and apostrophe ones?

like image 765
Ertuğrul Çetin Avatar asked Jan 04 '17 00:01

Ertuğrul Çetin


1 Answers

They are the "auto-promoting" versions of the normal math functions.

user> (* Long/MAX_VALUE 2)
ArithmeticException integer overflow  clojure.lang.Numbers.throwIntOverflow (Numbers.java:1501)
user> (*' Long/MAX_VALUE 2)
18446744073709551614N

They will return a larger data-type than the input if the output gets too big. This used to be the default behaviour early in Clojure, and then it was changed to throw an exception if the output of a math operation overflowed it's data type. This improved numeric performance and generally helped find bugs. In the five or so years since then surprisingly few people have complained about this change breaking anything. It was decided to keep the behaviour of throwing an exception on overflow because this is almost always a bug.

In practice, most of the time you will know when you are going to need to use BigIntegers and BigDecimals and can use the normal functions with these data types.

user> (* Long/MAX_VALUE 2N)
18446744073709551614N

In this example I used the normal * function, and passed it an argument that was of type BigInteger (that's what the N in 2N means to the clojure-reader)

There are a few cases where you really need to work with any size number without knowing it's size in advance and these functions come in handy. So far most of these examples for me are factorial examples on StackOverflow.

If you really want your math operation to overflow then you can use the explicitly unsafe math functions:

user> (unchecked-add Long/MAX_VALUE 2)
-9223372036854775807
like image 82
Arthur Ulfeldt Avatar answered Nov 05 '22 22:11

Arthur Ulfeldt