# Clojure

Od prazne liste do makroa

Nebojša Stričević

5. decembar 2013.

## Clojure

• pojavio se 2007.
• 1958. - prvi LISP

``````(defn- fib-iter
[max n i j]
(if (= n max)
j
(recur max
(inc n)
j
(+ i j)))) ``````

# Upozorenje

malo ću vas lagati

Jede liste!

## Prazna lista

``````> ()
() ``````

## Aritmetika

``> (+ 1 2)3``

## Aritmetika

``> (- 12 4)8``

## Aritmetika

``> (+ 1 2 3 4)10``

## Aritmetika

``> (* (- 12 8) (+ 1 2))12``

Kako teče evaluacija?

## Evaluacija

``> (* (- 12 8) (+ 1 2)); (* 4 (+ 1 2)); (* 4 3)12``

## Promenljive

``> (def a 3)a> (def b 4)b> (println a)3> (+ a b)7``

## Funkcije

``> (def add-2    (fn [n]      (+ n 2)))add-2> (add-2 4)6``

## Funkcije

``>(def more-than-5?   (fn [n]     (if (> n 5)       (println "Yes!")       (println "No...")))more-than-5?> (more-than-5? 2)"No..."``

## Liste

``> (def numbers (1 2 3 4 5))``

``Error! There is no function "1".``

## Liste

``> (def numbers '(1 2 3 4 5))numbers``

## Operacije sa listama

``> (def numbers '(1 2 3 4 5))numbers> (first numbers)1> (rest numbers)(2 3 4 5)``

``> (cons 0 numbers)(0 1 2 3 4 5)``

## Operacije sa listama

``> (def numbers '(1 2 3 4 5))numbers> (map add-2 numbers)(3 4 5 6 7)``

## Šta možemo stripati u listu?

``> (def code '(+ 1 2))code``

``> (println code)(+ 1 2)``

``> (eval code)3``

## Code as data

``> (def code '(+ 1 2))code``
``>(def new-code   (cons '- (rest code)))new-code``
``> (println new-code)(- 1 2)``
``> (eval new-code)-1``

## Code as string

• Ruby
• Python
• JavaScript
• ...

`` eval "1 + 2"``

## Proširivanje jezika

``(if (= 1 1)  (println "1 is indeed 1"))``

``(unless (= 1 1)  (println "1 is not 1"))``

## unless je funkcija!

``> (def unless    (function [condition code]      (if (not condition)        code)))> (unless (= 1 1)    (println "1 is not 1"))``

`` "1 is not 1"``

## unless je makro

``(defmacro unless [condition code]  '(if (not ~condition)    ~code))``
``> (unless (= 1 1)    (println "1 is not 1"))``
``> (if (not (= 1 1))    (println "1 is not 1"))``
``>``

## Java?

``// 1996.for (int i = 0; i < collection.size(); i++) {    SomeType var = collection.get(i);    ...}``

``// 2004.for (SomeType var : collection) {    ...}``

## Clojure

``(defmacro foreach [[sym coll] & body]  `(loop [coll# ~coll]    (when-let [[~sym & xs#] (seq coll#)]      ~@body      (recur xs#))))>(foreach [i numbers]   (println i))``

## Zašto Clojure?

• Lisp
• Functional Programming
• designed for Concurrency
• JVM
• Java interoperability

## Hvala

http://slid.es/strika/clojure

By strika

### Clojure

Od prazne liste do makroa

• 1,063