Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Clojure@NSU 00
Search
Nikita Prokopov
March 06, 2013
Programming
2
960
Clojure@NSU 00
Nikita Prokopov
March 06, 2013
Tweet
Share
More Decks by Nikita Prokopov
See All by Nikita Prokopov
DataScript for Web Development
tonsky
1
6.2k
Калифорнийский стартап в России @ NSU
tonsky
1
270
Clojure@Codefest 2013
tonsky
14
1.7k
Clojure@NSU 01
tonsky
1
770
Clojure@Echo 02 Библиотеки, web-стек, ClojureScript
tonsky
3
530
Clojure@Echo 01 Структуры данных, полиморфизм, интероп
tonsky
3
290
Clojure@Echo 00 обзор, concurrency
tonsky
3
480
Юзабилити инструментов разработчика
tonsky
0
180
Other Decks in Programming
See All in Programming
【第4回】関東Kaggler会「Kaggleは執筆に役立つ」
mipypf
0
1k
MCPとデザインシステムに立脚したデザインと実装の融合
yukukotani
3
1.1k
CSC305 Summer Lecture 12
javiergs
PRO
0
130
Claude Codeで挑むOSSコントリビュート
eycjur
0
190
ECS初心者の仲間 – TUIツール「e1s」の紹介
keidarcy
0
150
testingを眺める
matumoto
1
130
テストカバレッジ100%を10年続けて得られた学びと品質
mottyzzz
2
440
詳解!defer panic recover のしくみ / Understanding defer, panic, and recover
convto
0
210
go test -json そして testing.T.Attr / Kyoto.go #63
utgwkk
2
220
Honoアップデート 2025年夏
yusukebe
1
900
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
310
プロポーザル駆動学習 / Proposal-Driven Learning
mackey0225
2
350
Featured
See All Featured
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.5k
Fashionably flexible responsive web design (full day workshop)
malarkey
407
66k
How to train your dragon (web standard)
notwaldorf
96
6.2k
Agile that works and the tools we love
rasmusluckow
330
21k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
Designing Experiences People Love
moore
142
24k
Intergalactic Javascript Robots from Outer Space
tanoku
272
27k
Art, The Web, and Tiny UX
lynnandtonic
302
21k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
358
30k
Practical Orchestrator
shlominoach
190
11k
Speed Design
sergeychernyshev
32
1.1k
YesSQL, Process and Tooling at Scale
rocio
173
14k
Transcript
# mainstreamless ## Clojure 00 Никита Прокопов tonsky.livejournal.com 6 марта
2013
# Причины создания clojure.org/rationale Развитая платформа ЛИСП Функциональное программирование Concurrency
# JVM Быстрая Качественная Уровенем выше ОС, лучше абстракции Валом
библиотек Валом инструментов
# JVM Уважает платформу Писать джаву на кложе проще, чем
на джаве clj strings == java strings clj numbers == java numbers clj nil == java null
# LISP Гибкий Динамичный — новое для JVM Маленькое ядро
→ портируемость Почти нет синтаксиса Код-как-данные
# LISP def if do let quote var fn loop
recur throw try monitor-enter monitor-exit . new set!
# LISP REPL Открытость — всё управляемо Даже синтаксис!
# ФП Удобный инструмент First-class functions Lexical closures Ленивость Dynamic
typing
# Как это выглядит public class StringUtils { public static
boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } }
# Как это выглядит (defn blank? [s] (every? #(Character/isWhitespace %)
s))
# Как это выглядит public class StringUtils { public static
boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } } (defn blank? [s] (every? #(Character/isWhitespace %) s))
# Синтаксис method() method(arg) object.method(arg) Map<String, String> map = new
HashMap<String, String>(); map.put(“key”, “value”); (f) (f arg) (f object arg), (.method o a) (def map {:key “value”})
# Синтаксис (defn f [x y] (+ x y)) [1
2 3] (1 2 3) {:x 1 :y 2} #{:x :y :z}
# Философия См. youtube.com/clojuretv Особенно (!) Rich Hickey
# Открывайте данные Программы перемалывают данные Не прячьте их “It
is better to have 100 functions operate on one data structure than to have 10 functions operate on 10 data structures.”
# Открывайте данные distinct filter remove for keep keep-indexed cons
concat lazy-cat mapcat cycle interleave interpose rest next fnext nnext drop drop-while nthnext for take take-nth take-while butlast drop-last for flat- ten reverse sort sort-by shuffle split-at split-with partition partition-all partition-by map pmap mapcat for replace reductions map-indexed seque first ffirst nfirst second nth when-first last rand-nth zipmap into reduce set vec into-array to-array-2d frequen- cies group-by apply not-empty some reduce seq? eve- ry? not-every? not-any? empty? some filter doseq do- run doall realized? seq vals keys rseq subseq rsubseq lazy-seq repeatedly iterate repeat range line-seq resultset-seq re-seq tree-seq file-seq xml-seq itera-
# Decomplecting Var = value + time Object = state
+ identity + value Method = func + state + namespace Actors = what + who Loops = what + how ...
# Открытость Мультиметоды, протоколы Метаданные Predicate dispatch вместо pattern matching
Composable abstractions $().click().css() или (-> ($ ...) (click ) (css))
# Переиспользуемость Неймспейсится всё Нет custom reader, есть EDN Полиморфизм
через протоколы
# Комбинируемость Avoid things that do not compose Manual locking
Imperative code
# Concurrency ## Задача колония муравьев собирает пищу каждый муравей
— отдельный поток общая карта еды рисовать положение дел
# Concurrency ## Задача
# Concurrency ## Проблемы неатомарные операции согласованное принятие решений когерентное
состояние мира
# Проблемы многопоточного программирования «Мир» постоянно меняется Просадка скорости на
syncs Dead locks Live locks Легко ошибиться Сложно просчитать варианты Сложно тестировать
# Immutable data structures Легко шарить между потоками Операции атомарны
по определению Едят кучу памяти (медленно?)
# Persistent data structures «Умно» делят общие части Едят мало
памяти Быстрые (почти константная стоимость) Портированы в Scala :)
# List 1 2 3 list1 head tail list2 head
tail list3 head tail
# Vector v
# Vector v
# Vector v
# Vector v
# Vector v
# Vector v
# Vector v ... ...
# Vector v ... ... up to 32 elms log
32 (size)
# Vector v ... ... up to 32 elms log
32 (size) 00[00000][00000][00000][00000][00001][00100]
# Map ## Hash trie
# Map
# Atoms (def x (atom 1)) ;; #’user/x (swap! x
inc) ;; 2 (swap! x inc) ;; 3 (swap! x inc) ;; 10 (?) (swap! x #(Math/sin %)) ;; -0.544...
# Atoms 1 x
# Atoms 1 2 x (f 1)
# Atoms 1 2 x swap!
# Atoms 1 2 x
# Atoms 1 2 3 x (f 2)
# Atoms 1 2 3 x swap!
# Atoms 1 2 3 x
# Atoms 1 2 3 x @x
# Atoms 1 2 3 x (f (f 1)) @x
# Atoms Для «простого» mutable state Явно выделенная «мутация» Атомарное
изменение Любое значение — это всегда результат последовательного применения функций
# Atoms ## Конфликты 1 2 3 x (f 2)
−2
1 2 3 x (f −2) −2 −1 # Atoms
## Конфликты
1 2 3 x swap! −2 −1 # Atoms ##
Конфликты
# Agents (def x (agent 1)) ;; #’user/x (send x
inc) ;; #<Agent@73703457: 2> (send x inc) ;; #<Agent@73703457: 3> (send x (fn [a] (Thread/sleep 1000) (inc a))) ;; #<Agent@73703457: 3> @x ;; #<Agent@73703457: 3> @x ;; #<Agent@73703457: 4>
# Agent 2 g f h thread pool
# Agent 2 h g f thread pool
# Agent 2 h g thread pool f
# Agent 2 h g thread pool f (f 2)
# Agent 3 h g thread pool (f 2)
# Agent 3 h g thread pool
# Agent 3 h thread pool g
# Agent Unit of work Похож на atoms, только… Для
последовательных операций: heavy lifting, сохранение в файл, запись в сеть, конечные автоматы, … Выполняется в отдельном потоке Очередь сообщений Всегда наблюдаемое состояние
# STM Согласованное изменение состояния Проще рассуждать Сложнее ошибиться Composable
Агенты работают с STM!
# STM
# Concurrency Иммутабельность Персистентные структуры данных Software transactional memory Lock-free
Composable Безопасно!
# mainstreamless ## Clojure 00 Никита Прокопов tonsky.livejournal.com 6 марта
2013