Updated 2_On_Numbers_and_Arithmetic.txt

rhgraysonii authored
revision 63c9d42d30fd20c6abab59215088d0fac2a9b055
2_On_Numbers_and_Arithmetic
# Numbers and Arithmetic

As demonstrated earlier, we saw there is much that will feel comfortable with Clojure and artithmetic. In a brief review we should feel comfortable with the following examples:

(+ 1 2 3 4 5)
;=>15

(- 3 (+ 1 2))
;=> 0

(/ 2 3)
;=> 2/3

(/ 2.0 3)
;=>.66666666666...

Now, let us take a deeper look.

(type 4)
;=>java.lang.Long

This simple means it is a Java type. The long. In Java, all you really need to know about a long is that it uses one bit to store the type (positive or negative) of the number and allocates the other 63 its to storing the size of the number itself. If you try to exceed its maximum number size (2^63) it will give you an error. Clojure also offers other common types from Java

(type (short 0))
;=> java.lang.Short

Now, before we explain this. Let's try it in Ruby.

(type (int 11))
;=>java.lang.Integer

(type(byte 0))
;=> java.lang.Byte

(type 2.0)
;=> java.lang.Float

To express something precisely using fractions, the Ratio type comes into play.

(type(2/3))
;=> clojure.lang.Ratio

Now, before we explain this. Let's try it in Ruby.

Now, lets take a look into comparison and analysis here. We have some types that your standard OO programmer may not have encountered thus far depending on the areas they have dove in.

(= 2 2.0)
;=>false

(== 2 2.0)
;=>true

Now, before we explain this. Let's try it in Ruby.

2 == 2.0
>true

And, in JS,

2 == 2.0
>true

What is this hoopla? Well, in Clojure floats are considered an approximation. This is why we are allowed to express values more precisely using the Ratio type. Now, what if we want to use a number larger than the maximum of 2^63?

(type(5N))
;=>clojure.lang.BigInt

This allows us to write arbitrary precision integers. We can examine the value of integers in order with our typical "<" ">" "<=" ">=" operators.

(< 3 2 1)
;=>true

This allows us to ensure they are in descending order. We can increment and decrement as well.

(inc 1)
;=>2

(dec 1)
;=>0

This should give you a solid fundamental understanding of the nuances of Clojures arithmetic methods and data types. For a more in depth look at these structures check out [this documentation](http://clojure.org/cheatsheet). Again, no exercises this chapter. Just play around however you see fit in a concept that may not have clicked fully, or even one that blew your face off with awesome when you realized the approach's ingenuity.