Clojure - Arithmetic Operators


Advertisements

Clojure language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available in Clojure.

Operator Description Example
+ Addition of two operands (+ 1 2) will give 3
Subtracts second operand from the first (- 2 1) will give 1
* Multiplication of both operands (* 2 2) will give 4
/ Division of numerator by denominator (float (/ 3 2)) will give 1.5
inc Incremental operators used to increment the value of an operand by 1 inc 5 will give 6
dec Incremental operators used to decrement the value of an operand by 1 dec 5 will give 4
max Returns the largest of its arguments max 1 2 3 will return 3
min Returns the smallest of its arguments min 1 2 3 will return 1
rem Remainder of dividing the first number by the second rem 3 2 will give 1

Example

The following code snippet shows how the various operators can be used.

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (def x (+ 2 2))
   (println x)
   
   (def x (- 2 1))
   (println x)
   
   (def x (* 2 2))
   (println x)
   
   (def x (float(/ 2 1)))
   (println x)
   
   (def x (inc 2))
   (println x)
   
   (def x (dec 2))
   (println x)
   
   (def x (max 1 2 3))
   (println x)
   
   (def x (min 1 2 3))
   (println x)
   
   (def x (rem 3 2))
   (println x))
(Example)

The above program produces the following output.

Output

4
1
4
2.0
3
1
3
1
1
clojure_operators.htm
Advertisements