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 01
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Nikita Prokopov
March 20, 2013
Programming
780
1
Share
Clojure@NSU 01
Nikita Prokopov
March 20, 2013
More Decks by Nikita Prokopov
See All by Nikita Prokopov
DataScript for Web Development
tonsky
1
6.4k
Калифорнийский стартап в России @ NSU
tonsky
1
280
Clojure@Codefest 2013
tonsky
14
1.8k
Clojure@NSU 00
tonsky
2
970
Clojure@Echo 02 Библиотеки, web-стек, ClojureScript
tonsky
3
550
Clojure@Echo 01 Структуры данных, полиморфизм, интероп
tonsky
3
300
Clojure@Echo 00 обзор, concurrency
tonsky
3
490
Юзабилити инструментов разработчика
tonsky
0
190
Other Decks in Programming
See All in Programming
「OSSがあるなら自作するな」は AI時代も正しいか ── Build vs Adopt の新しい判断基準
kumorn5s
3
860
ハーネスエンジニアリングとは?
kinopeee
13
6.7k
ハーネスエンジニアリングにどう向き合うか 〜ルールファイルを超えて開発プロセスを設計する〜 / How to approach harness engineering
rkaga
27
19k
Spec Driven Development | AI Summit Vilnius
danielsogl
PRO
1
140
第3木曜LT会 #28
tinykitten
PRO
0
120
【26新卒研修】OpenAPI/Swagger REST API研修
dip_tech
PRO
0
140
実践ハーネスエンジニアリング:ステアリングループを実例から読み解く / Practical Harness Engineering: Understanding Steering Loops Through Real-World Examples
nrslib
2
2k
WebAssembly を読み込むベストプラクティス 2026年春版 / Best Practices for Loading WebAssembly (Spring 2026)
petamoriken
5
1.1k
tRPCの概要と少しだけパフォーマンス
misoton665
2
260
ついに来た!本格的なマルチクラウド時代の Google Cloud
maroon1st
0
370
GoogleCloudとterraform完全に理解した
terisuke
1
190
t *testing.T は どこからやってくるの?
otakakot
1
900
Featured
See All Featured
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
55
3.3k
Effective software design: The role of men in debugging patriarchy in IT @ Voxxed Days AMS
baasie
0
340
Writing Fast Ruby
sferik
630
63k
The AI Revolution Will Not Be Monopolized: How open-source beats economies of scale, even for LLMs
inesmontani
PRO
3
3.4k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
900
How Software Deployment tools have changed in the past 20 years
geshan
0
33k
Unlocking the hidden potential of vector embeddings in international SEO
frankvandijk
0
780
Leading Effective Engineering Teams in the AI Era
addyosmani
9
1.9k
A brief & incomplete history of UX Design for the World Wide Web: 1989–2019
jct
1
370
Practical Orchestrator
shlominoach
191
11k
How To Stay Up To Date on Web Technology
chriscoyier
790
250k
Stop Working from a Prison Cell
hatefulcrawdad
274
21k
Transcript
# mainstreamless ## Clojure 01 Никита Прокопов tonsky.livejournal.com 20 марта
2013
# Clojure web stack Servlet Netty Mongrel2 Http-kit Aleph Ring
Moustache Compojure Enlive Hiccup Laser ClojureScript Domina Enfocus Crate Javelin Reflex
# Ring Server ←→ app contract fn [request-map] → response-map
Похоже на WSGi (Python) github.com/ring-clojure/ring/blob/master/SPEC
# Ring { :uri :query-string :request-method :headers :body ... }
→ { :status :headers :body }
# Ring Нет реализации — нет зависимостей, багов, етц Маленькая
— легко реализовать Низкоуровневая Вход-выход — просто тестировать Веб-сокеты не засунешь
# Middleware (fn [handler ...] → handler’) ring.middleware: + Sessions
+ Cookies + Uploads + Form parsing ...
# Диспатчинг ## Moustache (def my-app (app [“hi”] {:get “hello
world only for GET!”} [“hi” name] {:get [“hello “ name]}))
# Диспатчинг ## Compojure (defroutes app (GET “/” [] “<h1>Hello
World</h1>”) (route/not-found “<h1>Page not found</h1>”))
# Templating — цветочки ## Hiccup (html [:span {:class “foo”}
“bar”]) <span class=”foo”>bar</span> (html [:div#foo.bar.baz “bang”]) <div id=”foo” class=”bar baz”>bang</div>
# Templating — цветочки ## Hiccup (defn with-cdn [cdn-url form]
(clojure.walk/postwalk (fn [node] (if (rel-asset-path? node) (cdn-url node) node) form)))
# Templating — ягодки ## Enlive Парсинг и трансформация HTML
Код отдельно от верстки Переиспользование snippets Модификации можно комбинировать Макросы!
# Templating — ягодки ## Enlive (at a-node [:a :selector]
a-transformation [:another :selector] another-transformation ...) (html/deftemplate index “tutorial/template1.html” [ctxt] [:p#message] (html/content (get ctxt :message “Nothing to see here”))
# Templating — ягодки ## Laser Еще более функциональный (laser/document
(laser/parse html) (laser/class= “meow”) (laser/content “omg”))
# Aleph Сетевая библиотека Общение через каналы Conforms to Ring,
только request и response разделены HTTP, WebSockets, TCP, UDP, Redis
# Aleph async (defn handler [response-channel request] (enqueue response-channel {:status
200 :headers {“content-type” “text/plain”} :body “Hello World”}))
# Aleph async (def handler (app [“sync”] {:get “response”} [“async”]
{:get (wrap-aleph-handler async-han- dler)})) (start-http-server (wrap-ring-handler handler) {:port 8080})
# Aleph async (def broadcast-channel (channel)) (defn chat-handler [ch handshake]
(receive ch (fn [name] (siphon (map* #(str name “: “ %) ch) broadcast-channel) (siphon broadcast-channel ch)))) (start-http-server chat-handler {:port 8080 :websocket true})
# http-kit Pure Java & Clojure, very small Server &
client Ring-compliant Websockets, long-polling, streaming extensions
# edn Data exchange format Based on Clojure syntax Rich
set of elements collections, symbols, keywords Extensible for new types Self-describing (no schema) Namespaces
# edn { :created_at #inst “1985-04-12T23:20:50.52Z” :id 209722238071619586 :id_str “209722238071619586”
:retweeted false :text “tweet” :com.google.maps/geo nil :entries { :user_mentions [ { :id 1001 :indices [0 16] :name “Petrov” } ] } }
# edn clojure.core/read-string clojure.edn/read-string (since 1.5)
# edn clojure.core/read-string clojure.edn/read-string (since 1.5) and cljs.reader/read-string
# ClojureScript
# Lessons learned from Node.js Писать клиент и сервер на
одном языке очень удобно! Только почему на JavaScript?
# ClojureScript JS is broken
# ClojureScript JS is fundamentally broken
# ClojureScript JS is fundamentally broken Синтаксические изменения не спасут
Нужно править семантику
# Что сломано? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые
операции
# CoffeeScript? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые операции
# CoffeeScript? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые операции
# CoffeeScript? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые операции
# CoffeeScript? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые операции
# CoffeeScript? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые операции
# CoffeeScript? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые операции
# CoffeeScript? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые операции
# CoffeeScript? Типы Структуры данных Зависимости Неймспейсы Полиморфизм Типовые операции
Меньше кнопок нажимать
# Как правильно? Состояние Иммутабельность ФП Макросы Строгая типизация Протоколы
# Как правильно? Стандартные решения для стандартных проблем
# Как правильно? Стандартные решения для стандартных проблем Реализаций import:
0 ООП-фреймворков: 0 Альтерн. синтаксисов: 0 Альтерн. коллекций: 0 Monad tutorials: 0
# Как работает? Компилируется на большой Clojure Генерирует Javascript для
Google Closure Compiler Оптимизируется Google Closure Compiler Зависимости через Goolge Closure Library
Notice Clojure (Rich Hickey) and Closure (Google)
# Компиляция? Dead code elimination Smart code compression Снимает browser
quirks Может увеличить производительность Debug :(
# Отличия от Clojure Однопоточный Compilation и macroexpansion только на
Clojure (no eval) Browser-connected REPL Native JS regexes
# Отличия от Clojure Atoms, but no Refs nor STM
No Vars No agents No symbol or var (def) metadata
# Отличия от Clojure (.foo o) => o.foo() (.-foo o)
=> o.foo
# Персистентные структуры данных Native JS impl http://www.50ply.com/cljs-bench/ 2-6 times
slower than JVM Google Chrome usually ×3-5 times faster than Safari / FF
# Персистентные структуры данных
# Персистентные структуры данных
# Зачем? Разработка больших приложений Организация кода Командная работа Переиспользуемость
кода Производительность, оптимизация
# Библиотеки No problem Нужен extern файл /** * @param
{(string|Object.<string,*>)} arg1 * @param {Object.<string,*>=} settings * @return {jQuery.jqXHR} */ jQuery.ajax = function(arg1, settings) {};
# Библиотеки ## jQuery $(“element“) .appen(“xyz”) .attr(“data-weight”, 70) .css(“left”, 156
+ “px”); (-> (js/$ “#element“) (.append “xyz“) (.attr “data-weight“ 70) (.css “left“ (str 156 “px”))
# Библиотеки ## jayq (def $interface (jq/$ :#interface)) (-> $interface
(jq/css {:background “blue”}) (jq/inner “Loading!”))
# DOM manipulation Domina Enfocus Crate Webfui Dommy
# DOM manipulation Domina ~ jQuery Enfocus ~ Enlive Crate
~ Hiccup Webfui ~ DOM isolation Dommy ~ Efficient macro-compile
# FRP javelin reflex shafty
# FRP ## Javelin (defn ^:export start [] (let [text
(form-cell “#text”) length (cell (count text))] (.focus (by-id “#text”)) (cell (html! “#count” “Length: %s” length))))
# CLJS on Node.js Faster startup times Native clients (node-webkit)
# Usecases ## Lighttable
# Usecases ## Prismatic
# Usecases ## Weathertable
# mainstreamless ## Clojure 01 Никита Прокопов tonsky.livejournal.com 20 марта
2013