Clojure
How, When, and Why?
(defn add-two-numbers [x y] (+ x y))
(defn wat? [no-idea*])
Clojure...
- ...is a Lisp for the JVM.
- ...and CLR, and JavaScript.
(let [d (java.util.Date.)] (.getTime d))
Clojure...
- ...is a dynamically typed Lisp for the JVM.
Pre-/Post-conditions
(defn some-like-it-even [x] {:pre [(even? x)] :post [(> % 0)]} x) ;; user=> (some-like-it-even 2) ;; 2 ;; user=> (some-like-it-even 3) ;; AssertionError Assert failed: (even? x) ;; user=> (some-like-it-even 0) ;; AssertionError Assert failed: (> % 0)
Typed Clojure
Clojure...
- ...is a functional, dynamically typed Lisp for the JVM.
Functional
- higher order functions
- persistent immutable data structures
Macros
- compile-time transformations of code
;; http://www.braveclojure.com/writing-macros/ (defmacro postfix-notation "I'm too indie for prefix notation" [expression] (conj (butlast expression) (last expression))) ;; (postfix-notation (1 1 +)) ;; => 2
Light Table
Leiningen
- "easy way to use Clojure" (also: only)
- declarative project configuration (dependencies, entry points, ...)
- everyone is using it
Use Case(s)
Motivation
- a lot of ugly PHP doing seq. data fetching & processing
- goal: parallelize!
- requirement: interaction with existing PHP code
Why Clojure?
- easy deployment
- basic familiarity with the language
- feature set seemed a good fit
- good excuse :)
PHP Interop
- ZeroMQ
- cljzmq (requires jzmq)
Databases
- Korma — SQL abstraction
-
(select my_table (fields [:id :a_field]) (where {:id 42}))
Databases
- Monger — a MongoDB Driver
-
(mc/insert db "my_documents" { :_id (ObjectId.) :an_awesome_key "an awesome value" })
Other / Smaller Libs
- twitter-api
- clj-http — an Apache HttpComponents Wrapper
- clj-time — a Joda Time Wrapper
Development Time
- ~ 2 weeks
Result
- ~ 1000 lines of Clojure code
- cleaner source, better SOC
- more flexible system
- completely decoupled an important part of the project
Deployment
cd myproject && lein uberjar
- push the JAR to the server
java -jar my_awesome_clojure_app.jar
Bottom Line
- interesting, exciting new language
- friendly, vibrant community
- different approach to certain problems
- very easy to get up & running (esp. with leiningen)
- easy to deploy (esp. if you're already running Java)
- good first step towards FP
to the moon & beyond