Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Speaker Deck
PRO
Sign in
Sign up for free
Clojure@NSU 01
Nikita Prokopov
March 20, 2013
Programming
1
710
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
4.8k
Калифорнийский стартап в России @ NSU
tonsky
1
240
Clojure@Codefest 2013
tonsky
14
1.7k
Clojure@NSU 00
tonsky
2
920
Clojure@Echo 02 Библиотеки, web-стек, ClojureScript
tonsky
3
420
Clojure@Echo 01 Структуры данных, полиморфизм, интероп
tonsky
3
260
Clojure@Echo 00 обзор, concurrency
tonsky
3
430
Юзабилити инструментов разработчика
tonsky
0
160
Other Decks in Programming
See All in Programming
iOSアプリの技術選択2022
tattn
6
2.2k
Micro Frontends with Module Federation: Beyond the Basics @jax2022
manfredsteyer
PRO
0
280
Android入門
hn410
0
300
WindowsコンテナDojo : 第1回 Visual StudioでWindowsコンテナアプリ作成
oniak3ibm
PRO
0
320
WindowsコンテナDojo:第2回 Windowsコンテナアプリのビルド、公開、デプロイ
oniak3ibm
PRO
0
140
Swift Concurrencyによる安全で快適な非同期処理
tattn
2
170
코드 품질 1% 올리기
pluu
1
920
microCMS × imgixを活用して品質とレスポンスを両立したポートフォリオサイトを作成した話
takehitogoto
0
390
読みやすいコードを書こう
yutorin
0
380
あなたの会社の古いシステム、なんとかしませんか?~システム刷新から考えるDX化への道筋とバリエーション~/webinar20220420-grapecity
grapecity_dev
0
130
バンドル最適化マニアクス at tfconf
mizchi
3
2k
Let's make a contract: the art of designing a Java API
mariofusco
0
160
Featured
See All Featured
Documentation Writing (for coders)
carmenhchung
48
2.5k
Three Pipe Problems
jasonvnalue
89
8.6k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
151
12k
Practical Orchestrator
shlominoach
178
8.6k
How New CSS Is Changing Everything About Graphic Design on the Web
jensimmons
212
11k
WebSockets: Embracing the real-time Web
robhawkes
57
5k
Side Projects
sachag
449
37k
How To Stay Up To Date on Web Technology
chriscoyier
780
250k
Java REST API Framework Comparison - PWX 2021
mraible
PRO
11
4.6k
5 minutes of I Can Smell Your CMS
philhawksworth
196
18k
The Cult of Friendly URLs
andyhume
68
4.7k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
314
19k
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