pivorak clojure by dmytro bignyak

Post on 16-Apr-2017

207 Views

Category:

Software

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Clojure ))))How not to be afraid of parentheses

Dmytro Bignyak

Me

Dmytro Bignyak

GitHub: deril Twitter: @derilok

It is not about

• in Ruby it takes 5 lines of code but in Clojure only 4

• I show you much code, how cool Clojure is

Clojure ≠ Closure

I ♥ Clojure

Is that easy?

(defn select "Returns a set of the elements for which pred is true" {:added "1.0"} [pred xset] (reduce (fn [s k] (if (pred k) s (disj s k))) xset xset))

Clojure is very powerful

• It is a functional language

• It has functional advantages

• Clojure can used as functional style

(map (partial * 10) [1 2 3]) ; => [10 20 30]

• It also can be used for structures

(defrecord Color [red green blue]) (def b (assoc a :alpha 0.1)) ; b => {:alpha 0.1, :red 0.5 :green 0.6, :blue 0.7}

Clojure is very useful when you want some

ASYNC

Clojure has 4 types of links

1. var (thread local)

2. atom (can be synchronically changed, but not coordinately)

3. agent (async state; analogue actor)

4. ref (can be synchronically and coordinately changed)

var

(def a 123) (println a) ; => 123

atom

(let [x (atom 0)] (println @x) ; => 0 (swap! x inc) (println @x)) ; => 1

agent

(def a (agent 0)) ; initial state

(send a inc) (println @a) ; => 1

(send a (fn [x] (Thread/sleep 100) (inc x))) (println @a) ; => 1

; in 100ms (println @a) ; => 2

• Agents change their state asynchronically

• In any time you can call deref and get the state of agent

Clojure can be used for MVCC (Multiversion Concurrency Control)(def account1 (ref 100) (def account2 (ref 0))

(dosync (alter account1 - 30) (alter account2 + 30))

(println @account1) ; => 70 (println @account2) ; => 30

(dosync (alter account1 * 0) (alter account2 / 0)) ; => ArithmeticException

; values weren’t changed (println @account1) ; => 70 (println @account2) ; => 30

I prefer core.async

Example core.async(defonce log-chan (chan))

(defn loop-worker [msg] (println msg))

(go-loop [] (let [msg (<! log-chan)] (loop-worker msg) (recur)))

Clojure (as all Lisps) is very powerful in metaprogramming

(defmacro unless [pred a b] `(if (not ~pred) ~a ~b))

(unless (> 1 10) (println "1 > 10. ok") (println "1 < 10. wat"))

Language is nothing without infrastructure

• Clojure uses JVM

• Eclipse, IDEA plugins

• Leiningen building tool

• Web frameworks (LuminusWeb, Noir)

• Async servers (https://github.com/ztellman/aleph)

ClojureScript (silver bullet for

JavaScript)

What’s next?

(println "Thank you!")

top related