More Related Content Similar to Clojure: Practical functional approach on JVM (20) Clojure: Practical functional approach on JVM29. Higher-Order Functions ;; integer as first class value (def a 10) ;; function as first class value (def b (fn [x] (+ x a))) ;; anonymous function #(+ a %) ;; function that generate a closure (def c (fn [x] #(+ x %))) ;; high order function (function as parameter) (def d (fn [f x] (f x a))) 65. State management ;;refs and STM (def a (ref 0)) (def b (ref 1)) (dosync (alter a inc) (alter b + @a)) @a @b ;;atoms (def a (atom 0)) (def b (atom 1)) (swap! a inc) (swap! b + @a) @a @b ;;agents (def a (agent 0)) (def b (agent 1)) (send a inc) (send b + @a) ;;thread local binding (def a 0) (def b 1) (binding [a 100] (+ b a)) a 76. Macro (defmacro cd "change current directory" [path & cmd] `(str "cd " ~path "; " ~ @cmd) ) (defmacro run "simply run a command" [cmd] `(str ~cmd "; ") ) 77. Macro (cd “/home/nsun” (run “rm -rf ./*”)) cd /home/nsun; rm -rf ./*; (macroexpand '(cd "/home/nsum" (run "rm -rf ./*"))) (clojure.core/str "cd " "/home/nsum" "; " (run "rm -rf ./*")) 83. Java Interop – Java for Clojure (import java.util.Date) (def now (Date.)) (.getTime now) (System/currentTimeMillis) 84. Java Interop - Clojure->Java (ns gen-class-test.core (:gen-class :state value :init init :constructors {[String] []} :methods [[printValue [String] void] ^{:static true} [version [] String]])) (defn version [] "1.0") (defn -init [name] [[] (atom {:name name})]) (defn -printValue [this prefix] (println (str prefix @(.value this)))) 93. Aleph (defcodec dummy-codec (finite-frame :int24 (string :utf8))) (defn echo-handler [ch client-info] (receive-all ch #(do (println %) (enqueue ch %)))) (start-tcp-server echo-handler {:port 1234, :frame dummy-codec}) Gloss codec Lamina queue Aleph 96. Ring (defn app [req] {:status 200 :headers {"Content-Type" "text/html"} :body "Hello World from Ring"}) Middleware Middleware Middleware Handler Middleware 97. Compojure framework (defroutes default-routes (GET "/rage/:id" [] get-rage) (GET "/rages/:channel" [] get-rages)) (defn get-rage [req] (let [id (:id (:params req))] (json-response (get-data id)))) (defroutes default-routes (GET "/rage/:id" [] get-rage) (GET "/rages/:channel" [] get-rages)) 98. Clojure JDBC DDL ;; database config (def db {:classname "org.hsqldb.jdbc.JDBCDriver" :subprotocol "hsqldb" :subname "testdb" :user "SA" :password ""}) (defn create-db [] (jdbc/with-connection db (jdbc/create-table table-name [:name "VARCHAR(32)" "PRIMARY KEY"] [:submitter "VARCHAR(32)"] [:title "VARCHAR(512)"]))) 99. Clojure JDBC DML (jdbc/with-connection db (jdbc/with-query-results results [(str "select * from " (name table-name))] (into [] results)))