(lojure)



(lojure)

1 2


clojure-2014-slides


On Github niquola / clojure-2014-slides

(lojure

by niquola DevConf 2014

Teamlead of health samurai

@ waveaccess/choice-hospital-systems

github/niquola / twt g+ fb

History (Mon, 13 Feb 2006 13:43:02 +0900)

          Ruby is a language designed in the following steps:

          * take a simple lisp language (like one prior to CL).
          * remove macros, s-expression.
          * add simple object system (much simpler than CLOS).
          * add blocks, inspired by higher order functions.
          * add methods found in Smalltalk.
          * add functionality found in Perl (in OO way).

          So, Ruby was a Lisp originally, in theory.
          Let's call it MatzLisp from now on. ;-)
        

LISP, MacCarthy 1960

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 Raymond
        

(what? clojure)

(A LISP
 for Functional Programming
 on JVM
 designed for Concurency
 by Rich Hickey)

(lang?)

  • Primitives ?
  • Composition ?
  • Abstraction ?

(primitives? :data)

nil
"string"
100.0 ;; number
:keyword
symbol
(this is the list)
[:this :is :the :vector]
{:i "am", :the "Map"}
#{\s \e \t}

All Data Types

are immutable

  • list ()
  • vector []
  • hash-map {}
  • set #{}

Chris Okasaki

Persistent (tries)

(primitives? :code)

(def symbol init?)
(if test then else?)
(do exprs*)
(let [bindings* ] exprs*)
(quote form)
(var symbol)
(fn name? [params* ] exprs*)
(loop [bindings* ] exprs*)
(recur exprs*)
(throw expr)
(try expr* catch-clause* finally-clause?)

(composition? :data)

[{:name "admin" :roles #{:admin}}
 {:name "user"  :roles #{:author}}]

(composition? :code)

a + b*3

(ast)

[:function, :myfn, [:x, :y],
  [:+,
    [:*, :x, :x],
    [:*, :y, :y]]]

[:myfn, 3, 6]

(ast)

[function myfn [x y]
  [+
    [* x x]
    [* y y]]]

[myfn 3 6]

(hello lisp)

(defn myfn [x y]
  (+ (* x x)
     (* y y)))

(myfn 3 6)

{[;not(so-much(punctuation));]}

function myfn(x,y){ //4
  return x*x + y*y; //2
}; //2

myfn(3,6); //4
// sum: 12

(homoiconicity)

(CODE is DATA)

(uniform)

(class module method statements ...)
(only s-expression! )

(syntax)

form = (op arg arg)
arg = form | data

(everething s-expression)

 (built-in-form)
 (function-call args list)
 (macros-call args and forms)

(most of good staf)

(defn f-name [args] body)
(cond (pred1) (expr1)
      (pred2) (expr2))
(for [x xs] body)

(extendable small core)

(meta language)

(DSL)

(defmacro)

(defmacro unless
  [pred f1 f2]
  (list 'if (list 'not pred) f1 f2))

(defmacro unless
  [pred f1 f2]
  `(if (not (~pred)) f1 f2))

(unless (= 1 2)
  (print "ok")
  (print "not"))

(abstraction? :data)

ADT - abstract data type

(constructor ...) => tp
(selector tp) => ...
(operations tp) => ...

separate data & behavior

(Polimorphism?)

  collection = array
  collection = set

  collection.add(element)

(oopish polimorphism)

methods bundled with data

Expression problem

| type   | op1  | op2  | ? |
| ------ |:----:| ----:|   |
| tp1    | x    | x    |   |
| tp2    | x    | x    |   |
| tp3    | x    | x    |   |
-> ?

add new type

add new behavior (interface)

(protocols)

(defprotocol Speaker
  (say [this]))

(deftype Rubist [name age city]
  Speaker
  (say [this]
      (str "Hello i'm ruby")))

(deftype Javoid [name age city]
  Speaker
  (say [this]
      (str "Hello i'm java")))

(dynamic dispatch)

(defmulti encounter
   (fn [x y]
     [(:Species x) (:Species y)]))

(defmethod encounter
  [:Bunny :Lion] [b l]
  :run-away)

(defmethod encounter
  [:Bunny :Bunny] [b l]
  :sex)

(abstraction? :code)

Functional Programming

First class functions

Immutable datatypes & Pure Functions

Higher Order Functions

Lambda Calculus

abstraction and application

An Introduction to Functional Programming Through Lambda Calculus

Functional Programming

a more mathematical view

functions get values and produce values

(Pure Functions & Immutable Data)

referential transparency

functional core

Essential & Acidental

complexity

Shared Mutable State

Out of the tar pit

Value

a value is something that doesn't change

Identity & Working Models

Models need identity for the same reasons humans need identity - to represent the world.

State

Identity & Value changing in time

State & Identity

  • No way to obtain the state independent of the identity other than copying it.
  • No way to observe a stable state (even to copy it) without blocking others from changing it.
  • No way to associate the identity's state with a different value other than in-place memory mutation.

Value

a = 42
b = a
a = a + 1
b = ?

Reference

a = [1]
b = a
a = concat(a, 1)
b = ?

Clojure Programming

Calculate values functionaly

Use Refs & Agents for identity

clojure docs

(expicite state)

(def my-atom (atom 0))
@my-atom
(swap! my-atom inc)

Concurency

Immutability makes much of the problem go away

Software Transactional Memory & agent systems

do the hard part

(Higher Order Functions)

(abstraction? :code)

(Higher Order Functions)

(use 'clojure.walk)
(def thing 
  {:page/tags [{:tag/category "lslsls"}]})
(postwalk 
   #(if(keyword? %)

(keyword (name %)) %) thing)
=> {:tags [{:category "lslsls"}]}

Посетители деревьев Clojure

(destructuring & pattern-matching)

 (let [[a b] [1 2]

 {meth :request-method} req

 {:keys [x y] :or {x 0 y 0}} point]
   ...)

(abstraction? :code)

(meta lang)

homoiconicity

uniform syntax

macros

(midje)

(fact "here desc"
  (+ 1 2) => 3
  (conj [1] 2) => (contains 1 2))

(core.async)

 (def ch (chan))
 (go
  (while true
    (let [v (<! ch)]
     (println "Read: " v))))

 (go (>! ch "hi")
     (<! (timeout 5000))
     (>! ch "there"))

(korma)

 (defentity users)
 (select users
   (where {:active true})
   (order :created)
   (limit 5)
   (offset 3))

(loco)

 (def model
   [($in :x 1 6)
    ($in :y 3 7)
    ($= ($+ :x :y) 10)])

 (solutions model)
 ;=> ({:y 7, :x 3} {:y 6, :x 4}...

(core.logic)

 (run* [q]
   (fresh [x y]
     (== [x 2] [1 y])
     (== q [x y])))

 ;=> ([1 2])

(paradigm :as (a library))

(require
   '[clojure.core.typed :refer [ann]])

(ann  bar [Number -> Number])
(defn bar [b]
      (+ 2 (foo b)))

(repl driven dev)

 nREPL server started on port 49222
 on host 127.0.0.1

 user=> ...

(dynamism & fp)

Languages and Platforms

  • JVM
  • CLR
  • JSVM

interop

(.toUpperCase "fred")
(System/getProperty "java.vm.version")
(.. System
    (getProperties)
    (get "os.name"))

Rich Hickey

Books

Resources

thx?