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.1k
Калифорнийский стартап в России @ 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
11年かかって やっとVibe Codingに 時代が追いつきましたね
yimajo
1
260
CLI ツールを Go ライブラリ として再実装する理由 / Why reimplement a CLI tool as a Go library
ktr_0731
3
1k
あのころの iPod を どうにか再生させたい
orumin
2
2.4k
LLMOpsのパフォーマンスを支える技術と現場で実践した改善
po3rin
8
790
新世界の理解
koriym
0
130
GitHub Copilotの全体像と活用のヒント AI駆動開発の最初の一歩
74th
7
2.4k
MCPで実現できる、Webサービス利用体験について
syumai
7
2.5k
変化を楽しむエンジニアリング ~ いままでとこれから ~
murajun1978
0
710
kiroでゲームを作ってみた
iriikeita
0
150
AIに安心して任せるためにTypeScriptで一意な型を作ろう
arfes0e2b3c
0
340
[DevinMeetupTokyo2025] コード書かせないDevinの使い方
takumiyoshikawa
2
280
あなたとJIT, 今すぐアセンブ ル
sisshiki1969
1
610
Featured
See All Featured
Docker and Python
trallard
45
3.5k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
34
3.1k
The Pragmatic Product Professional
lauravandoore
36
6.8k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
139
34k
Automating Front-end Workflow
addyosmani
1370
200k
Building Flexible Design Systems
yeseniaperezcruz
328
39k
Imperfection Machines: The Place of Print at Facebook
scottboms
267
13k
Six Lessons from altMBA
skipperchong
28
3.9k
What's in a price? How to price your products and services
michaelherold
246
12k
It's Worth the Effort
3n
185
28k
The MySQL Ecosystem @ GitHub 2015
samlambert
251
13k
Rails Girls Zürich Keynote
gr2m
95
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