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
Nikita Prokopov
March 20, 2013
Programming
1
770
Clojure@NSU 01
Nikita Prokopov
March 20, 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 00
tonsky
2
950
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
LINEヤフー データグループ紹介
lycorp_recruit_jp
0
770
iOSアプリ開発で 関数型プログラミングを実現する The Composable Architectureの紹介
yimajo
2
210
ASP.NETアプリケーションのモダナイズ インフラ編
tomokusaba
1
400
既存デザインを変更せずにタップ領域を広げる方法
tahia910
1
240
なぜ適用するか、移行して理解するClean Architecture 〜構造を超えて設計を継承する〜 / Why Apply, Migrate and Understand Clean Architecture - Inherit Design Beyond Structure
seike460
PRO
1
420
Select API from Kotlin Coroutine
jmatsu
1
190
Using AI Tools Around Software Development
inouehi
0
1.2k
20250628_非エンジニアがバイブコーディングしてみた
ponponmikankan
0
220
Datadog RUM 本番導入までの道
shinter61
1
310
GoのWebAssembly活用パターン紹介
syumai
3
10k
ドメインモデリングにおける抽象の役割、tagless-finalによるDSL構築、そして型安全な最適化
knih
11
2k
生成AIで日々のエラー調査を進めたい
yuyaabo
0
630
Featured
See All Featured
Thoughts on Productivity
jonyablonski
69
4.7k
Building a Modern Day E-commerce SEO Strategy
aleyda
41
7.3k
The MySQL Ecosystem @ GitHub 2015
samlambert
251
13k
GraphQLの誤解/rethinking-graphql
sonatard
71
11k
The Power of CSS Pseudo Elements
geoffreycrofte
77
5.8k
A designer walks into a library…
pauljervisheath
206
24k
Principles of Awesome APIs and How to Build Them.
keavy
126
17k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
29
1.8k
Making Projects Easy
brettharned
116
6.3k
Facilitating Awesome Meetings
lara
54
6.4k
Imperfection Machines: The Place of Print at Facebook
scottboms
267
13k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
15
1.5k
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