Clojure

Dialect of programming language Lisp

Clojure is a modern dialect of Lisp, created by Rich Hickey in 2007. It encourages functional and concurrent programming styles.

As well as other Lisp dialects, Clojure syntax is based on S-expressions, and source code can be treated as data. But Clojure is incompatible with other dialects.

Main Clojure implementation compiles source code to JVM bytecode, so Clojure interacts with Java nicely. Other implementations allow to compile source code so as to run it on Microsoft Common Language Runtime or as JavaScript.

Main features:

  • concurrency is based on immutable data values and mutable references to them, which are used to manage parallel access from different threads.
  • functions are first-class objects.
  • maps, sets and vectors are supported as first-class objects.
  • “lazy” sequences.
  • instead of loops with side-effects the emphasis is done on recursion and higher-order functions.

Clojure logo
Clojure logo

Examples:

Hello, World!:

Example for versions Clojure 1.0.0, Clojure 1.1.0
(printf "Hello, World!")

Factorial:

Example for versions Clojure 1.0.0, Clojure 1.1.0

This example uses recursive factorial definition. range with one argument generates a list of numbers from 0 (inclusive) to this number (exclusive). str concatenates strings. dec is decrement, equivalent to (- x 1). doseg is Clojure-style loop.

(defn factorial [x]
  (if (< x 2)
    1
    (* x (factorial (dec x)))))

(doseq [i (range 17)]
  (println (str (str i "! = ") (factorial i))))

Factorial:

Example for versions Clojure 1.0.0, Clojure 1.1.0

To calculate factorial of a number, one can create a range of numbers from 2 to this number and calculate the product of these numbers (function apply).

(doseq [i (range 17)]
  (println (str (str i "! = ") (apply * (range 2 (inc i))))))

Fibonacci numbers:

Example for versions Clojure 1.0.0, Clojure 1.1.0

This example uses recursive definition of Fibonacci numbers.

(defn fibonacci [x]
  (if (< x 2)
    x
    (+ (fibonacci (- x 1)) (fibonacci (- x 2)) )))

(doseq [i (range 1 17)]
  (print (str (fibonacci i) ", ")))
(println "...")

Quadratic equation:

Example for versions Clojure 1.0.0, Clojure 1.1.0
(defn solve-quadratic [a b c]
  (if (= a 0)
    "Not a quadratic equation."
    (let [D (- (* b b) (* 4 a c))
          k1 (- 0 b)
          k2 (* 2 a)]
         (if (= D 0)
            (str "x = " (/ k1 k2))
            (if (> D 0)
                (let [k3 (Math/sqrt D)]
                     (str (str "x1 = " (/ (+ k1 k3) k2) (str "\nx2 = " (/ (- k1 k3) k2)))))
                (let [k3 (Math/sqrt (- 0 D))]
                     (str (str (str (str "x1 = (" (/ k1 k2)) (str ", " (/ k3 k2))) ")\nx2 = (") (str (str (/ k1 k2) ", ") (str (- 0 (/ k3 k2)) ")") ))
                ))))))

(import '(java.util Scanner))
(def scan (Scanner. *in*))
(def a (.nextInt scan))
(def b (.nextInt scan))
(def c (.nextInt scan))
(println (solve-quadratic a b c))