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
940
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
5.6k
Калифорнийский стартап в России @ NSU
tonsky
1
250
Clojure@Codefest 2013
tonsky
14
1.7k
Clojure@NSU 01
tonsky
1
740
Clojure@Echo 02 Библиотеки, web-стек, ClojureScript
tonsky
3
460
Clojure@Echo 01 Структуры данных, полиморфизм, интероп
tonsky
3
280
Clojure@Echo 00 обзор, concurrency
tonsky
3
460
Юзабилити инструментов разработчика
tonsky
0
170
Other Decks in Programming
See All in Programming
効率化に挑戦してみたらモバイル開発が少し快適になった話
ryunakayama
0
130
単体テストを書かない技術 #phpcon_odawara
o0h
PRO
27
8.3k
Random\Randomizer クラスで日常のあれこれを解決しよう! / Random\Randomizer class solves familiar trouble
cocoeyes02
0
250
ADRを一年運用してみた/adr_after_a_year
hanhan1978
7
2.4k
Git Lint
bkuhlmann
4
750
Polars入門
daikikatsuragawa
1
100
ONE WEDGE_company_guide
1wedge_one
0
500
Node.js v22 で変わること
yosuke_furukawa
PRO
9
3.5k
Amazon SQSコンシューマー疎結合への旅 - 出張! #DevelopersIO IT技術ブログの中の人が語る勉強会 #3
quiver
0
280
見た目から始める生産性向上
ikumatadokoro
8
910
SIMD Parallel Programming with the Vector API
josepaumard
0
190
Ruby Pattern Matching
bkuhlmann
0
930
Featured
See All Featured
The Straight Up "How To Draw Better" Workshop
denniskardys
227
130k
What's in a price? How to price your products and services
michaelherold
237
11k
Building Effective Engineering Teams - LeadDev
addyosmani
28
1.9k
KATA
mclloyd
15
12k
Building Applications with DynamoDB
mza
88
5.6k
The Mythical Team-Month
searls
216
42k
Done Done
chrislema
178
15k
How STYLIGHT went responsive
nonsquared
92
4.8k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
121
39k
Building an army of robots
kneath
300
41k
Building Better People: How to give real-time feedback that sticks.
wjessup
355
18k
Robots, Beer and Maslow
schacon
PRO
155
7.9k
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