Skip to content

Instantly share code, notes, and snippets.

@ujihisa
Created July 11, 2013 18:52
Show Gist options
  • Save ujihisa/5978137 to your computer and use it in GitHub Desktop.
Save ujihisa/5978137 to your computer and use it in GitHub Desktop.

Introduction to Clojure

Clojure

  • imperative
  • S-Expression
  • anti object-oriented

programming language

  • on JVM
  • on JavaScript

Hello world

(prn "hello world!")

Hello world (2)

(def hello-world "Bonjour!")

(defn -main []
  (prn hello-world))

Use functions

  • JavaScript
console.log((x + 10) * 2);
  • Clojure
(prn (* (+ x 10) 2))
  • Or
(prn (-> (+ x 10) (* 2)))

Lambda

(fn [x]
  (* (+ x 10) 2))
  • Or with macro
#(* (+ % 10) 2)

Other data structures

  • Symbol :abc

  • Vector

[1 2 3 4 5]
["a" :b \c]
  • Map (dictionary; hash)
{:a "hi" :b []}

Good

easy to

  • read
    • macro / immutability / naming
  • write
    • syntax
  • make it concurrent
    • immutability / future / STM

Good naming

  • defn
  • prn
  • cons/conj
(cons 1 [2 3]) ;=> [1 2 3]
(conj [2 3] 1) ;=> [2 3 1]

Good naming

(if a
  b
  c)

(if a
  (do
    b1
    b2)
  c)

(when a
  b1
  c2)

Comment

  • comment
  • #_
(prn #_(+ 2 (* 3 4)) 999)

JVM

  • Clojure is good partly because it's on JVM

  • Clojure is terribly bad because it's on JVM

JVM

  • Java
x.m(a, b);
C.f(x);
  • Clojure
(.m x a b)
(C/f x)

Performance

  • slow to start, fast to run

  • faster to start, slower to run compare to Scala

Performance

Ruby (2.1.0)

  • hello world: 0.02sec
  • fib(40): 15.58sec

Clojure (1.5.1)

  • hello world: 1.19sec
  • fib(40): 4.84sec

Practical?

Yes!

  • Leiningen (build tool)

  • clojars.org (library; ecosystem)

  • tools that depend on libraries for java

tricky parts

  • No continuations (call/cc)
  • No automatic tail call optimization
  • No alternative string literals
  • (No user-defined reader macro)

(System/exit 0)

  • Clojure

  • made by Rich Hickey since 2007

  • google "tryclojure" to run some code even without installing clojure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment