PDF herunterladen

Werbung
CLOJURE
A PRACTICAL LISP FOR THE JVM
LT 54 - Ralph Guderlei
WARUM CLOJURE?
Lisp
REPL zur interaktiven Entwicklung
sehr gute Java-Interop
funktional
dynamisch typisiert
http://clojure.org/rationale
Lisp is worth learning for the profound
enlightenment experience you will have when
you finally get it; that experience will make you a
better programmer for the rest of your days, even
if you never actually use Lisp itself a lot.
Eric S. Raymond
LISP
LISt Processor
Lots of Irritating Silly Parenthesis
Erste Version: 1958
Dialekte: Scheme (1975), Common Lisp (1984), Clojure (2007)
Einfluß auf viele Sprachen: Ruby, Javascript, Smalltalk, ...
REPL
SYMBOLIC EXPRESSIONS
(operator operand1 operand2 ...)
Operand: Literal (Variable, Datenstruktur, ...) oder SExpression
Präfix-Notation
Code ist gültige Clojure-Datenstuktur (Homoikonizität) ->
Makros
BEISPIEL: IF
(if (< i 0)
0
(do-sth-with i))
DATENSTRUKTUREN
Booleans, Strings, Characters, Zahlen, Keywords
Maps
{:foo true "bar" 12/3}
Listen, Vektoren, Sets
FUNKTIONEN
(defn multiply
"multiplies two numbers x and y"
[x y]
(* x y))
implizite returns
Docstring
JAVA INTEROP
(def s (.toUpperCase "foo")) ;; => "FOO"
(doto (new MyEntity)
(.setA "foo")
(.setB 42))
JAVA INTEROP - GOODIES
Definition und Implementierung von Interfaces
(defprotocol)
Polymorphic dispatch
(defmulti), (defmethod)
Definition von Typen
(deftype), (defrecord)
REALES BEISPIEL
(defroutes app-routes
(context "/items" [] (defroutes items-routes
(GET "/" [] (get-all-items))
(POST "/" {body :body} (create-item body))
(context "/:id" [id] (defroutes item-routes
(PUT "/" {body :body} (update-item id body))
(DELETE "/" [] (delete-item id)))))))
(def app
(-> (handler/api app-routes)
(middleware/wrap-json-body)
(middleware/wrap-json-response)))
REALES BEISPIEL
(defn get-all-items []
(let [conn (mg/connect)
db (mg/get-db conn "lt")]
{:body (mc/find-maps db "items")}))
(defn create-item [todo-item]
(let [conn (mg/connect)
db (mg/get-db conn "lt")
oid (ObjectId.)]
(mc/insert db "items" (merge todo-item {:_id oid}))
{:status 201}))
FAZIT
sehr einfache und konsistente Syntax
REPL: schelles Feedback bei der Entwicklung
interessante Bibliotheken (REST, core.async, core.logic)
gute Ergänzung zu Java (funktional, dynamische Typisierung)
optionale Features: Typisierung, AOT-Compiler, Java-Interop
ClojureScript
Nachteil: IDE-Support
Online: Clojure for the Brave and True
Herunterladen