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
730
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
Front-end application development, Symfony-style(s)
dunglas
2
1.9k
Why 1 + 1 = 2 in Swift?
1plus4
1
600
CircleCIを活用して AWSへの継続的デリバリーを 実践する
coconala_engineer
1
230
TYPO3 v13 – The road to LTS: What's new and new APIs
luisasofie_xoxo
0
180
From Spring Boot 2 to Spring Boot 3 with Java 21 and Jakarta EE
ivargrimstad
0
1k
入門 AWS Amplify Gen2 / Introduction to AWS Amplify Gen2
genkiogasawara
1
300
Introduction for Open Source Swift Workshop
giginet
PRO
0
1k
品質とスピードを両立: TypeScriptの柔軟な型システムをバックエンドで活用する
kosui
8
2.2k
コードレビューで学ぶ!Kotlinオブジェクト指向デザインパターン
akkie76
2
170
try! Swift Tokyo 2024のLT枠に採択されたプロポーザルを出すときに考えていたこと
ski
0
330
CA.swift19 恋するAIアプリ開発の裏側
oskmr
0
320
エンターテイメント業界で利用されるAWS
demuyan
0
200
Featured
See All Featured
GraphQLの誤解/rethinking-graphql
sonatard
49
9.2k
The World Runs on Bad Software
bkeepers
PRO
61
6.7k
Art, The Web, and Tiny UX
lynnandtonic
288
19k
The Brand Is Dead. Long Live the Brand.
mthomps
48
27k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
29
6k
Java REST API Framework Comparison - PWX 2021
mraible
PRO
18
6.9k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
6
990
Building Your Own Lightsaber
phodgson
97
5.7k
We Have a Design System, Now What?
morganepeng
42
6.7k
GraphQLとの向き合い方2022年版
quramy
29
12k
Robots, Beer and Maslow
schacon
PRO
154
7.9k
Optimising Largest Contentful Paint
csswizardry
7
2.3k
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