Question: What are those math functions end with apostrophe in Clojure?

Question

What are those math functions end with apostrophe in Clojure?

Answers 1
Added at 2017-01-04 01:01
Tags
Question

There are some functions(math fns) that their name end with apostrophe.

Like: +', *', -'

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

Answers
nr: #1 dodano: 2017-01-04 01:01

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
Source Show
◀ Wstecz