SlideShare a Scribd company logo
1 of 45
Download to read offline
Learn basics of Clojure/script and
Reagent
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 1
About me
@matystl – twitter, github
currently working in web development
worked in C++, C#, Java, Dart, JavaScript, Ruby
love learning new things
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 2
Clojure
dynamic, LISP-like programing language hosted on JVM
started in 2007 by Rich Hickey
current version 1.7 (June 30 2015)
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 3
ClojureScript
compiler for Clojure that targets JavaScript (use Google Closure
compiler for production builds)
started in 2012
same syntax and features as Clojure with few unsupported ones (STM,
threads)
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 4
Why it’s worth to know it
Clojure has great community
different programming paradigm than mainstream OOP
excellent presentations from Rich Hickey and David Nolen
it’s fun
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 5
Defining features
LISP syntax
◦ Macros
Immutability
Functional programing
Concurrency
Native host (Java/Javascript) interoperability
REPL-based
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 6
Leiningen
the easiest way to use Clojure
project automation and declarative configuration
dependency management
project generation
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 7
Read Eval Print Loop
Clojure repl
◦ lein repl
Clojurescript repl
◦ lein new re-frame <project-name>
◦ creates folder with clojurescript project with figwheel, reagent, re-frame prepared
◦ cd <project-name> && lein figwheel dev – download
dependencies and run webserver
◦ http://localhost:3449 – open in browser and in console appear appropriate
clojurescript repl
◦ write (in-ns 'folder.core) to get to correct namespace
◦ on linux use rlwrap and put it before lein to have proper console like
history and cursor movement
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 8
For Light Table users
◦ Light table is build in clojure so you can evaluate forms inside of it in it’s
clojure environment
◦ create folder with some file in it
(ns folder.file)
(+ 1 2)
◦ place cursor inside (+ 1| 2) hit Ctrl + Enter to evaluate it and see result
instantly (on first try wait to connect to repl)
◦ place cursor on some symbol (|+ 1 2) and hit Ctrl + D to see
documentation
◦ Ctrl + space open quick search
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 9
Syntax
numbers - 47
ratios - 22/7 (only in Clojure not in ClojureScript)
strings – "hello“, "world"
characters - a b c (as strings in JS)
symbols - foo, bar
keywords - :a, :bar
Booleans – true/false
null - nil
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 10
Syntax - collections
Lists – (1 2 3 4)
Vectors – [1 2 3 4]
Maps – {:a 1 "b" 2} or {:a 1, "b" 2}
Sets - #{1 2 :a "hello"}
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 11
Syntax
That’s it. No other syntax is needed(Few shortcuts exists).
Data structures are code.
Homoiconic
Data literals stand for themselves except:
◦ Lists
◦ Symbols
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 12
Semantics
Usually list are evaluated(in REPL, your code)
First element is function to be called and rest is arguments passed to
that function. Arguments are evaluated before passing to function
(except for macros).
(+ 1 2) ; => 3
(add 1 (add 2 3)); add(1, add(2,3))
for suppressing evaluation add ' - '(+ 2 3) this will be list also in
repl and code
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 13
Documentation
(doc +)
-------------------------
cljs.core/+
[x]
Returns the sum of nums. (+) returns 0.
(find-doc "trim")
-------------------------
subvec
[v start end]
Returns ....
-------------------------
trim-v
([handler])
Middleware ...
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 14
Hello world
(ns folder.filename)
(defn hello
"An example function – documentation string"
[argument]
(println "Hello" argument))
(hello "World!")
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 15
Basics
(def simple-variable 5)
(fn [arg1 arg2] (+ arg1 arg2))
(def one (fn [] 1))
(defn add [arg1 arg2] (+ arg1 arg2))
(defn add-multiple-arity
([] 0)
([a] (add a 0))
([a b] (+ a b)))
#(+ 10 %) ;=> (fn [%] (+ 10 %))
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 16
Variables inside function - let
(defn message [a b]
(let [c (+ a b)
d (* c 15)]
(/ d 12)))
; function message(a, b) {
; const c = a + b;
; const d = c * 15;
; return (d/12);
;}
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 17
Collection operation – vector,
list, map, set
Collections are immutable, operation return new instances
get, count, vec, conj, first, rest, peek, pop,
into, nth, assoc, dissoc, contains?, disj
http://clojure.org/cheatsheet
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 18
Some example
(conj [1 2 3] 5) ; => [1 2 3 5]
(conj '(1 2 3) 5) ; => (5 1 2 3)
(assoc {} :a 5) ; => {:a 5}
(dissoc {:a 5} :a) ; => {}
(conj #{} :a) ; => #{:a}
(disj #{:a} :a) ; => #{}
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 19
Map access
(def m {:a 5 "b" 7})
(get m :a) ; => 5
(m :a) ; map is function from key to value
(:a m) ; keyword can retrieve itself from map and set
(get m "b") ; => 7
(m "b") ; => 7
("b" m) ; error
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 20
Map manipulation
(update m key func a2 a3 ...)
call (func (get key m) a2 a3 ...) and update m under key with new value
and return it
(update {:counter 0} :counter + 2) ; => {:counter 2}
for nested maps/vectors you can use update-in which take key path
(update-in m [key1 key2 ...] func a2 a3)
(update-in {:a {:b 5}} [:a :b] inc) ; => {:a {:b 6}}
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 21
Sequences
Not a data structure – source of values in some order
can be lazy(infinite)
most sequence functions return sequence
(range 3) ; => (0 1 2)
(seq {:a 5 :b 10}) ; => ([:a 5] [:b 10])
(seq []) ; => nil
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 22
Sequences - operations
(map inc [1 2 3]) ; => (2 3 4)
(map + [1 2 3] [20 40 60]) ; => (21 42 63)
(take 2 [1 2 3 4]) ; => (1 2)
take drop take-while drop-while filter remove
partition group-by sort shuffle reverse mapcat flatten
concat
repeat repeatedly cycle interpose interleave iterate
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 23
apply
(apply func arg-seq)
(+ 1 2 3) ; => 6
(+ [1 2 3]) ; => [1 2 3]
(apply + [1 2 3]); => 6
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 24
Sequence - results
(vec (filter even? (range 10)))
(set (map inc (range 10)))
(apply hash-map (range 10))
(apply str (interpose , (range 4)))
(into {} [[:x 1] [:y 2]])
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 25
Sequence – results 2
(reduce func init coll)
(some func coll)
(every? func coll)
remember laziness is hell for side-effects so put them at end
(take 4 (map println (range 100)))
(doseq [i (range 5)] (println i)) – iteration for side
effects
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 26
Flow control
everything is expression and return value
expression for side-effects return nil
(if test then else?)
(do exp1 exp2 ...)
(when test exp1 exp2 ...)
(cond test1 exp1 test2 exp2 ...)
(case test-val val1 exp1 val2 exp2 ...)
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 27
Flow control – imperative loop
(loop [i 0 j 0]
(println i i)
(if (< i 10)
(recur (inc i) (+ 2 b))))
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 28
Destructuring
can be used in function declaration, let binding and other bindings
(defn f [a b & rest] res)
(f 1 2 3 4) ; => (3 4)
[a b & rest :as whole-list]
(defn f [{the-a :a the-b :b}] '(:result the-a
the-b))
(f {:a 5 :b 7}) ; => '(:result 5 7)
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 29
Destructuring - 2
{a :a :as whole} ; same as in vector
works recursively
(let [[[x1 y1] [x2 y2]] [[1 2] [4 5]]]
[x1 x2 y1 y2]) ; => [1 4 2 5]
{{c :c :as inner} :a} ; => {:a {:c 10}}
if name will be same as keyword you can use this helper
(let [{:keys [x y]} {:x 1 :y 2}]
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 30
Identity, state and values
clojure has multiple explicit representation for identity
identity - a stable logical entity associated with a series of
different values over time
state is value of identity in particular time
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 31
Identity, state and values -
atom
atom is identy which can hold changing value in time
(def a (atom 0))
read value with
(deref a) or @a
set value with swap!
(swap! atom f a2? a3?)
can be shared between threads and swap is atomic operation
can be observed for changes
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 32
Identity, state and values -
other
other primitives are refs, vars, agent
refs are interesting because they implement transactions in
memory(STM) between multiple threads
not supported in ClojureScript
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 33
What now?
Continue with reagent and re-frame or
you are eagerly waiting to code?
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 34
Namespaces
every file has own namespace matching structure folder.file defined by macro
ns
require import other functionality into current namespace
usage of items from required namespace with
◦ name-of-imported-namespace/what-i-want-to-use
(ns reagent-tutorial.core
(:require [clojure.string :as string]
[reagent.core :as r]))
(def s (r/atom 0))
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 35
Javascript interoperability
use js/ prefix to access js global namespace
◦ js/document js/window js/console js/date
for data structure conversion there are helpers
◦ js->clj clj->js
functions from clojure are javascript functions
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 36
Javascript interoperability - 2
invoking js function from clojure
(.hello someObject a1 a2) ; someObject.hello(a1, a2);
accessing property
(.-name someObject) ; someObject.name
setting property
(set! (.-name someObject) value)
; someObject.name = value;
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 37
Reagent
simple ClojureScript interface to React
building blogs are functions, data, atoms
uses Hiccup-like markup no jsx
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 38
Reagent – simple component
(defn some-component []
[:div
[:h3 "I am a component!"]
[:p.someclass
[:span {:style {:color "red"}} " Red color "]
" text."]])
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 39
Reagent – render into dom
(ns example
(:require [reagent.core :as r]))
(r/render-component [some-component]
(.-body js/document))
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 40
Reagent – use of other
component
(defn child [name]
[:p "Hi, I am " name])
(defn childcaller []
[child "Foo Bar"])
(defn childcaller []
(child "Foo Bar"))
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 41
Reagent – usage of atoms
(def counter (r/atom 0))
(defn comp []
[:div
"Value of counter is:" @counter
[:div {:on-click #(swap! counter inc)} "inc"])
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 42
Reagent – local state
local let to create atom with state and return rendering function
(defn test3 []
(let [c (reagent/atom 0)]
(fn []
[:div
"Value of counter " @c
[:button {:on-click #(swap! c inc)} "inc"]
])))
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 43
Re-frame
Reagent is only V so for building application you need more
Re-frame is library and more importantly pattern how to develop
complicated SPA with Reagent
implementation is 200LOC description 800LOC
https://github.com/Day8/re-frame
if you want to try it read description and try it
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 44
Thanks!
QUESTIONS?
BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 45

More Related Content

What's hot

What's hot (20)

The best language in the world
The best language in the worldThe best language in the world
The best language in the world
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
 
Mini-curso JavaFX Aula3 UFPB
Mini-curso JavaFX Aula3 UFPBMini-curso JavaFX Aula3 UFPB
Mini-curso JavaFX Aula3 UFPB
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
Hems
HemsHems
Hems
 
Mini-curso JavaFX Aula2
Mini-curso JavaFX Aula2Mini-curso JavaFX Aula2
Mini-curso JavaFX Aula2
 
Mini-curso JavaFX Aula1
Mini-curso JavaFX Aula1Mini-curso JavaFX Aula1
Mini-curso JavaFX Aula1
 
Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Java file
Java fileJava file
Java file
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
C#
C#C#
C#
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 

Viewers also liked

Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
elliando dias
 

Viewers also liked (7)

Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in Clojure
 
Getting Started With Datascript and Reagent
Getting Started With Datascript and ReagentGetting Started With Datascript and Reagent
Getting Started With Datascript and Reagent
 
Reagents
ReagentsReagents
Reagents
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
 
Enjoyable Front-end Development with Reagent
Enjoyable Front-end Development with ReagentEnjoyable Front-end Development with Reagent
Enjoyable Front-end Development with Reagent
 
Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
CLI utility in ClojureScript running on Node.js
CLI utility in ClojureScript running on Node.jsCLI utility in ClojureScript running on Node.js
CLI utility in ClojureScript running on Node.js
 

Similar to Learn basics of Clojure/script and Reagent

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
g3_nittala
 

Similar to Learn basics of Clojure/script and Reagent (20)

C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle Scala
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Matplotlib
MatplotlibMatplotlib
Matplotlib
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.ppt
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

Learn basics of Clojure/script and Reagent

  • 1. Learn basics of Clojure/script and Reagent BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 1
  • 2. About me @matystl – twitter, github currently working in web development worked in C++, C#, Java, Dart, JavaScript, Ruby love learning new things BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 2
  • 3. Clojure dynamic, LISP-like programing language hosted on JVM started in 2007 by Rich Hickey current version 1.7 (June 30 2015) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 3
  • 4. ClojureScript compiler for Clojure that targets JavaScript (use Google Closure compiler for production builds) started in 2012 same syntax and features as Clojure with few unsupported ones (STM, threads) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 4
  • 5. Why it’s worth to know it Clojure has great community different programming paradigm than mainstream OOP excellent presentations from Rich Hickey and David Nolen it’s fun BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 5
  • 6. Defining features LISP syntax ◦ Macros Immutability Functional programing Concurrency Native host (Java/Javascript) interoperability REPL-based BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 6
  • 7. Leiningen the easiest way to use Clojure project automation and declarative configuration dependency management project generation BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 7
  • 8. Read Eval Print Loop Clojure repl ◦ lein repl Clojurescript repl ◦ lein new re-frame <project-name> ◦ creates folder with clojurescript project with figwheel, reagent, re-frame prepared ◦ cd <project-name> && lein figwheel dev – download dependencies and run webserver ◦ http://localhost:3449 – open in browser and in console appear appropriate clojurescript repl ◦ write (in-ns 'folder.core) to get to correct namespace ◦ on linux use rlwrap and put it before lein to have proper console like history and cursor movement BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 8
  • 9. For Light Table users ◦ Light table is build in clojure so you can evaluate forms inside of it in it’s clojure environment ◦ create folder with some file in it (ns folder.file) (+ 1 2) ◦ place cursor inside (+ 1| 2) hit Ctrl + Enter to evaluate it and see result instantly (on first try wait to connect to repl) ◦ place cursor on some symbol (|+ 1 2) and hit Ctrl + D to see documentation ◦ Ctrl + space open quick search BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 9
  • 10. Syntax numbers - 47 ratios - 22/7 (only in Clojure not in ClojureScript) strings – "hello“, "world" characters - a b c (as strings in JS) symbols - foo, bar keywords - :a, :bar Booleans – true/false null - nil BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 10
  • 11. Syntax - collections Lists – (1 2 3 4) Vectors – [1 2 3 4] Maps – {:a 1 "b" 2} or {:a 1, "b" 2} Sets - #{1 2 :a "hello"} BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 11
  • 12. Syntax That’s it. No other syntax is needed(Few shortcuts exists). Data structures are code. Homoiconic Data literals stand for themselves except: ◦ Lists ◦ Symbols BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 12
  • 13. Semantics Usually list are evaluated(in REPL, your code) First element is function to be called and rest is arguments passed to that function. Arguments are evaluated before passing to function (except for macros). (+ 1 2) ; => 3 (add 1 (add 2 3)); add(1, add(2,3)) for suppressing evaluation add ' - '(+ 2 3) this will be list also in repl and code BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 13
  • 14. Documentation (doc +) ------------------------- cljs.core/+ [x] Returns the sum of nums. (+) returns 0. (find-doc "trim") ------------------------- subvec [v start end] Returns .... ------------------------- trim-v ([handler]) Middleware ... BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 14
  • 15. Hello world (ns folder.filename) (defn hello "An example function – documentation string" [argument] (println "Hello" argument)) (hello "World!") BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 15
  • 16. Basics (def simple-variable 5) (fn [arg1 arg2] (+ arg1 arg2)) (def one (fn [] 1)) (defn add [arg1 arg2] (+ arg1 arg2)) (defn add-multiple-arity ([] 0) ([a] (add a 0)) ([a b] (+ a b))) #(+ 10 %) ;=> (fn [%] (+ 10 %)) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 16
  • 17. Variables inside function - let (defn message [a b] (let [c (+ a b) d (* c 15)] (/ d 12))) ; function message(a, b) { ; const c = a + b; ; const d = c * 15; ; return (d/12); ;} BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 17
  • 18. Collection operation – vector, list, map, set Collections are immutable, operation return new instances get, count, vec, conj, first, rest, peek, pop, into, nth, assoc, dissoc, contains?, disj http://clojure.org/cheatsheet BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 18
  • 19. Some example (conj [1 2 3] 5) ; => [1 2 3 5] (conj '(1 2 3) 5) ; => (5 1 2 3) (assoc {} :a 5) ; => {:a 5} (dissoc {:a 5} :a) ; => {} (conj #{} :a) ; => #{:a} (disj #{:a} :a) ; => #{} BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 19
  • 20. Map access (def m {:a 5 "b" 7}) (get m :a) ; => 5 (m :a) ; map is function from key to value (:a m) ; keyword can retrieve itself from map and set (get m "b") ; => 7 (m "b") ; => 7 ("b" m) ; error BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 20
  • 21. Map manipulation (update m key func a2 a3 ...) call (func (get key m) a2 a3 ...) and update m under key with new value and return it (update {:counter 0} :counter + 2) ; => {:counter 2} for nested maps/vectors you can use update-in which take key path (update-in m [key1 key2 ...] func a2 a3) (update-in {:a {:b 5}} [:a :b] inc) ; => {:a {:b 6}} BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 21
  • 22. Sequences Not a data structure – source of values in some order can be lazy(infinite) most sequence functions return sequence (range 3) ; => (0 1 2) (seq {:a 5 :b 10}) ; => ([:a 5] [:b 10]) (seq []) ; => nil BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 22
  • 23. Sequences - operations (map inc [1 2 3]) ; => (2 3 4) (map + [1 2 3] [20 40 60]) ; => (21 42 63) (take 2 [1 2 3 4]) ; => (1 2) take drop take-while drop-while filter remove partition group-by sort shuffle reverse mapcat flatten concat repeat repeatedly cycle interpose interleave iterate BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 23
  • 24. apply (apply func arg-seq) (+ 1 2 3) ; => 6 (+ [1 2 3]) ; => [1 2 3] (apply + [1 2 3]); => 6 BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 24
  • 25. Sequence - results (vec (filter even? (range 10))) (set (map inc (range 10))) (apply hash-map (range 10)) (apply str (interpose , (range 4))) (into {} [[:x 1] [:y 2]]) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 25
  • 26. Sequence – results 2 (reduce func init coll) (some func coll) (every? func coll) remember laziness is hell for side-effects so put them at end (take 4 (map println (range 100))) (doseq [i (range 5)] (println i)) – iteration for side effects BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 26
  • 27. Flow control everything is expression and return value expression for side-effects return nil (if test then else?) (do exp1 exp2 ...) (when test exp1 exp2 ...) (cond test1 exp1 test2 exp2 ...) (case test-val val1 exp1 val2 exp2 ...) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 27
  • 28. Flow control – imperative loop (loop [i 0 j 0] (println i i) (if (< i 10) (recur (inc i) (+ 2 b)))) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 28
  • 29. Destructuring can be used in function declaration, let binding and other bindings (defn f [a b & rest] res) (f 1 2 3 4) ; => (3 4) [a b & rest :as whole-list] (defn f [{the-a :a the-b :b}] '(:result the-a the-b)) (f {:a 5 :b 7}) ; => '(:result 5 7) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 29
  • 30. Destructuring - 2 {a :a :as whole} ; same as in vector works recursively (let [[[x1 y1] [x2 y2]] [[1 2] [4 5]]] [x1 x2 y1 y2]) ; => [1 4 2 5] {{c :c :as inner} :a} ; => {:a {:c 10}} if name will be same as keyword you can use this helper (let [{:keys [x y]} {:x 1 :y 2}] BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 30
  • 31. Identity, state and values clojure has multiple explicit representation for identity identity - a stable logical entity associated with a series of different values over time state is value of identity in particular time BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 31
  • 32. Identity, state and values - atom atom is identy which can hold changing value in time (def a (atom 0)) read value with (deref a) or @a set value with swap! (swap! atom f a2? a3?) can be shared between threads and swap is atomic operation can be observed for changes BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 32
  • 33. Identity, state and values - other other primitives are refs, vars, agent refs are interesting because they implement transactions in memory(STM) between multiple threads not supported in ClojureScript BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 33
  • 34. What now? Continue with reagent and re-frame or you are eagerly waiting to code? BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 34
  • 35. Namespaces every file has own namespace matching structure folder.file defined by macro ns require import other functionality into current namespace usage of items from required namespace with ◦ name-of-imported-namespace/what-i-want-to-use (ns reagent-tutorial.core (:require [clojure.string :as string] [reagent.core :as r])) (def s (r/atom 0)) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 35
  • 36. Javascript interoperability use js/ prefix to access js global namespace ◦ js/document js/window js/console js/date for data structure conversion there are helpers ◦ js->clj clj->js functions from clojure are javascript functions BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 36
  • 37. Javascript interoperability - 2 invoking js function from clojure (.hello someObject a1 a2) ; someObject.hello(a1, a2); accessing property (.-name someObject) ; someObject.name setting property (set! (.-name someObject) value) ; someObject.name = value; BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 37
  • 38. Reagent simple ClojureScript interface to React building blogs are functions, data, atoms uses Hiccup-like markup no jsx BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 38
  • 39. Reagent – simple component (defn some-component [] [:div [:h3 "I am a component!"] [:p.someclass [:span {:style {:color "red"}} " Red color "] " text."]]) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 39
  • 40. Reagent – render into dom (ns example (:require [reagent.core :as r])) (r/render-component [some-component] (.-body js/document)) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 40
  • 41. Reagent – use of other component (defn child [name] [:p "Hi, I am " name]) (defn childcaller [] [child "Foo Bar"]) (defn childcaller [] (child "Foo Bar")) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 41
  • 42. Reagent – usage of atoms (def counter (r/atom 0)) (defn comp [] [:div "Value of counter is:" @counter [:div {:on-click #(swap! counter inc)} "inc"]) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 42
  • 43. Reagent – local state local let to create atom with state and return rendering function (defn test3 [] (let [c (reagent/atom 0)] (fn [] [:div "Value of counter " @c [:button {:on-click #(swap! c inc)} "inc"] ]))) BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 43
  • 44. Re-frame Reagent is only V so for building application you need more Re-frame is library and more importantly pattern how to develop complicated SPA with Reagent implementation is 200LOC description 800LOC https://github.com/Day8/re-frame if you want to try it read description and try it BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 44
  • 45. Thanks! QUESTIONS? BASICS OF CLOJURE/SCRIPT AND REAGENT @REACTIVE2015 BY MATY 45