FP / Clojure

Clojure

Funkcionálne programovanie

História

LISP

REPL

Read–eval–print loop

Dialekty

Clojure

Clojure

Clojure

Hodnoty

1 2.8       ; numbers
"hello"     ; string
\e          ; char
hello       ; symbol
:world      ; keyword
true false  ; boolean
nil

Štruktúry

(1 2 3)         ; list
[1 2 3]         ; vector
{:a 1, :b 2}    ; map
#{1 2 3}        ; set

Zoznamy majú špeciálny význam

(max 1 3)   ; => 3
(+ 1 3)     ; => 4

Zoznam bez vyhodnocovania:

(quote (max 1 3))  ; => (max 1 3)
'(max 1 3)         ; => (max 1 3)

Variabilný počet argumentov

(max 1 3 5 4)   ; => 5
(apply max [1 3 5 4])   ; => 5

Definícia

(def size 10)
(def message "Hello world")

Funkcia

(fn [x y] (+ x y))  ; anonymná (lambda)
#(+ %1 %2)          ; skrátený zápis

(defn sum [x y] (+ x y))  ; pomenovaná

Podmienky

(fn format-legend [x]
  (if (= 0 (mod x 5))
      (str x)
      ""))

Lokálne premenné

(defn histogram [values]
  (let [height   (apply max values)
        width    (count values)
        legend-l (legend-line width)
        legend-c (legend-column height)
        body     (histogram-body values)]
    (unlines (beside legend-c (above body legend-l)))))

Príklady