Clojure
Implementation of programming language LispClojure is the main implementation of the language of the same name. It compiles source code to JVM bytecode and runs it on Java Virtual Machine, thus providing access to Java functions.
Clojure is distributed under Eclipse Public License.
Links:
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.0This 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.0To 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.0This 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))
Comments
]]>blog comments powered by Disqus
]]>