Casual Clojure Programming - Beginner's Notes [BETA]
Clojure as a language has a very simple syntax; its "operational" side, however, is somehow cryptic. This page is mostly a series of aide memoires - a list of all those "tokens" which I found hard to memorize.
The Quick and Dirty Method
If you are writing a "program" with a very short lifetime, then you can just
save it in a
.clj file and tell Clojure itself to execute it.
Here is an expendable program (
scratch.clj) to calculate one quadratic
;; scratch.clj (defn quad "solve a quadratic equation of the form ax^2 + bx + c" [a b c] (let [r (- (* b b) (* 4 a c)) w (Math/sqrt r) d (* 2 a)] (list (/ (+ (- b) w) d) (/ (- (- b) w) d)))) (println (quad 6 7 -3))
... and here is how to run it on the command-line using the Clojure 1.8.0 "interpreter":
java -cp /full/path/to/clojure-1.8.0.jar clojure.main scratch.clj
As Simple As Possible with Leiningen
Let's say you want to write a quick & dirty Clojure program (actually, just a function) to solve some little task. Even in this case, we will create a Leiningen project - after all, it can be used to host in the future all kinds of throwaway functions.
Creating a new project is easy ("$" is the Linux command-line prompt) (we'll
$ lein new goodies
Navigate into the new directory (
cd goodies), start your favorite editor
and change the file
./goodies/src/goodies/core.clj so that it looks like this:
(ns goodies.core) ;; something trivial, no need for fancy semantic (defn plus [a b] (+ a b))
Go back to your command line and start the project's REPL (
lein repl) and
user=> (use :reload-all '[goodies.core]) nil user=> (plus 2 3) 5