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
280
Clojure@Codefest 2013
tonsky
14
1.7k
Clojure@NSU 01
tonsky
1
770
Clojure@Echo 02 Библиотеки, web-стек, ClojureScript
tonsky
3
540
Clojure@Echo 01 Структуры данных, полиморфизм, интероп
tonsky
3
290
Clojure@Echo 00 обзор, concurrency
tonsky
3
480
Юзабилити инструментов разработчика
tonsky
0
180
Other Decks in Programming
See All in Programming
スマホから Youtube Shortsを見られないようにする
lemolatoon
27
33k
pnpm に provenance のダウングレード を検出する PR を出してみた
ryo_manba
1
150
What Spring Developers Should Know About Jakarta EE
ivargrimstad
0
400
オープンソースソフトウェアへの解像度🔬
utam0k
17
3.1k
CSC509 Lecture 08
javiergs
PRO
0
230
バッチ処理を「状態の記録」から「事実の記録」へ
panda728
PRO
0
180
CSC509 Lecture 07
javiergs
PRO
0
240
Things You Thought You Didn’t Need To Care About That Have a Big Impact On Your Job
hollycummins
0
250
品質ワークショップをやってみた
nealle
0
600
AI Coding Meetup #3 - 導入セッション / ai-coding-meetup-3
izumin5210
0
3.4k
SODA - FACT BOOK(JP)
sodainc
1
8.6k
NIKKEI Tech Talk#38
cipepser
0
120
Featured
See All Featured
KATA
mclloyd
PRO
32
15k
Thoughts on Productivity
jonyablonski
70
4.9k
jQuery: Nuts, Bolts and Bling
dougneiner
65
7.9k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
12
1.2k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
48
9.7k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
657
61k
The Language of Interfaces
destraynor
162
25k
Scaling GitHub
holman
463
140k
Speed Design
sergeychernyshev
32
1.2k
Practical Orchestrator
shlominoach
190
11k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
115
20k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.2k
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