SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Introduction to ClojureIntroduction to Clojure
Sidharth Khattri
Knoldus Software LLP
Sidharth Khattri
Knoldus Software LLP
● Clojure is a Functional Lisp (List Processing) which runs on JVM.
● It extends the principle of Code-as-Data system to include Maps and Vectors.
Everything in clojure is written inside a data structure referred to as the
S-expressions, i.e nested lists.
Eg: (/ 4 (+ 1 2)) => ?
● Clojure is a Functional Lisp (List Processing) which runs on JVM.
● It extends the principle of Code-as-Data system to include Maps and Vectors.
Everything in clojure is written inside a data structure referred to as the
S-expressions, i.e nested lists.
Eg: (/ 4 (+ 1 2)) => ?
Function Name Arguments
● Every operation in clojure is done using a Post-Fix notation
● Experimenting with clojure is quite easy. In order to get started with
clojure you need to follow the instructions on http://leiningen.org/ to
set up clojure environment on your system. Leningen is used for
project automation.
● Most popular IDE used for clojure is LightTable which can be
download from http://www.lighttable.com/
● You can fire up clojure's repl on linux terminal using:
lein repl or you can directly use a Live REPL in LightTable.
● You can also use clojure in Eclipse using CounterClockwise plugin.
● Everything that you need to know about clojure can be found in the
clojure cheatsheet at the following url: http://clojure.org/cheatsheet
● Even though a lot of parentheses can confuse programmers at first,
LightTable(IDE) can make programming in clojure really easy. A sample of
what usage of parentheses I'm talking about:
(filter #(if(zero? (rem % 3)) true) (map #(+ % 1) (range 10)))
=> ?
● The above code in LightTable should look something like this:
● Last line of a function can return another function, i.e a Higher Order
Function as illustrated in the following example:
(defn attribute [who?]
(if (= who? "superman")
#(str "Superman " %)
(fn[x] (str "Human " x))))
((attribute "superman") "Flying") => "Superman Flying"
(if 0
“Yee! True”
“Huh! False”) => ?
(if 1
“Yee! True”
“Huh! False”) => ?
Concept of truthy and falsy
(if 0
“Yee! True”
“Huh! False”) => “Yee! True”
(if 1
“Yee! True”
“Huh! False”) => “Yee! True”
Concept of truthy and falsy
Concept of truthy and falsy
Everything in clojure is true except false or nil
So,
(if nil
“Yee! True”
“Huh! False”) => “Huh! False”
Data Structures
● Clojure supports a number of data structures:
Lists, Vectors, Maps, Sets
● All clojure data structures are persistent data structures. Internally
they're implemented as a tree.
● Simplest way to define these data structures:
'(1 2 3) defines a list
[1 2 3] defines a vector
#{1 2 3} defines a set
{:1 “one” :2 “two”} defines a map
Nesting
● Searching and updating nested structures is very easy.
● Searching:
(def n {:india {:newdelhi {:knoldus {:address "30/29, 1st Floor, East Patel Nagar"}}}
:usa {:california {:knoldus {:address "743, Catamaran Street "}}}})
user=> (get-in n [:india :newdelhi])
Returns {:knoldus {:address "30/29, 1st Floor, East Patel Nagar"}}
● Updating:
(assoc-in n [:india :newdelhi :knoldus :number] 911142316525)
Returns {:india {:newdelhi {:knoldus {:number 911142316525, :address "30/29, 1st Floor, East Patel
Nagar"}}}, :usa {:california {:knoldus {:address "743, Catamaran Street "}}}}
● Remember that the value of “n” hasn't changed in any case.
Threading Operators
The previous code that we used:
(filter #(if(zero? (rem % 3)) true) (map #(+ % 1) (range 10)))
Is same as:
(->> (range 10)
(map #(+ % 1))
(filter #(if (zero? (rem % 3)) true)))
The threaded version is much cleaner
Threading Operators
In Nested structures example that we used:
(def n {:india {:newdelhi {:knoldus {:address "30/29, 1st Floor, East Patel Nagar"}}}
:usa {:california {:knoldus {:address "743, Catamaran Street "}}}})
We can use:
(-> n :india :newdelhi :knoldus :address)
Instead of:
(:address (:knoldus (:newdelhi (:india n))))
Loops
● For loop:
(for [x (range 1 10) :when (even? x)] x)
=> (2 4 6 8)
● While loop:
(while 0 (println “hello”))
● Loops with side effects:
(dotimes [x 5] (print x)) => 01234nil
(doseq [x [3 2 1]] (print x)) => 321nil
Binding Form - let
● We use the “let” form to bind data structures to symbols.
● Example:
(let [x 10
y 11
m (* x y)]
m)
user=> m
Binding Form - let
● We can also use let binding for destructuring:
● (defn index-sum [v & i]
(let [[x :as ind] (map #(get v %) i)]
(reduce + ind)))
(index-sum [1 2 3 4 5 6 7 8 9] 1 3 5) => ?
Built-in Parallelism
● “map” function will take more time as compared to the “pmap” function:
(time (doall (map (fn[x] (Thread/sleep 3000) (+ x 5)) (range 1 5))))
=> "Elapsed time: 12000.99432 msecs"
(6 7 8 9)
(time (doall (pmap (fn[x] (Thread/sleep 3000) (+ x 5)) (range 1 5))))
=> "Elapsed time: 3002.989534 msecs"
(6 7 8 9)
Futures
● Futures can be used to send any calculation intensive work in the
background while continuing with some other work.
● Defining futures:
(def f (future some-calculation-intensive-work))
● Example:
(defn show-result[]
;;do things
(def f (future some-calculation-intensive-work))
;;prepare gui to display result
@f) ;;wait until the result is returned
Atoms, refs and agents
● Atoms, refs and agents are the three options available for maintaining non-
local mutable state in clojure
➔ Atoms are for Uncoordinated Synchronous access
to a single Identity.
➔ Refs are for Coordinated Synchronous access
to Many Identities.
➔ Agents are for Uncoordinated Asynchronous access
to a single Identity.
Atoms
● Defining an atom:
(def a (atom {:a 1}))
● Getting the value stored in an atom:
(deref a) or @a
● Changing the value of an atom:
(swap! a #(assoc % :b 2)) => {:a 1 :b 2}
or
(reset! a 0) => Exception or changed value?
Refs
● Defining refs:
(def tasks-to-be-done (ref #{2 9 4}))
(def tasks-done (ref #{1 3 5}))
● Coordinated change:
(dosync
(commute tasks-to-be-done disj 2)
(commute tasks-done conj 2))
● Accessing values of refs:
@tasks-to-be-done => #{4 9}
@tasks-to-be-done => #{1 2 3 5}
Agents
● Can be useful in fork/join solutions.
● Defining an agent:
(def a (agent 0))
● Dispatching actions to an agent:
(dotimes [x 3] (send-off a (fn[x] (Thread/sleep 3000) (inc x))))
@a => ?
● In case we want to wait until the above code snippet has finished processing,
we can use:
(await a)
Arrays
● Defining an array:
(def a1 (make-array Integer/TYPE 3))
(pprint a1) => [0, 0, 0]
(def a2 (make-array Integer/TYPE 2 3))
(pprint a2) => [[0, 0, 0], [0, 0, 0]]
● (def a3 (to-array [1 2 3 4 5]))
(pprint a3) => [1, 2, 3, 4, 5]
Arrays
● Manipulating arrays:
(def a1 (make-array Integer/TYPE 3))
(aset a1 1 10))
(pprint a1) => [0, 10, 0]
(def a2 (make-array Integer/TYPE 2 3))
(aset (aget a2 0) 1 10)
(pprint a2) => [[0, 10, 0], [0, 0, 0]]
Datatypes
● defrecord creates an immutable persistent map (class-type datatype)
(defrecord Hobbit [fname lname address])
(defrecord Address [street town city])
(def bb (Hobbit. "Bilbo" "Baggins" (Address. "Bagshot row" "Hobbiton" "Shire")))
● user=> bb
#user.Hobbit{:fname "Bilbo", :lname "Baggins", :address #user.Address{:street "Bagshot
row", :town "Hobbiton", :city "Shire"}}
● (-> bb :address :city)
“Shire”
Datatypes
● deftype creates a bare-bones object (class-type datatype). Preferred for java
inter operability.
(deftype Hobbit [fname lname address])
(deftype Address [street town city])
(def bb (Hobbit. "Bilbo" "Baggins" (Address. "Bagshot row" "Hobbiton" "Shire")))
● user=> bb
#<Hobbit user.Hobbit@476c6b9c>
● (.street (.address bb))
"Bagshot row"
Protocols
● Dataype are used to implement protocols or interfaces.
(defprotocol Dialogue
(deliver-dialogue [d]))
(defrecord Where? [place]
Dialogue
(deliver-dialogue [d] (str "One does not simply walk into " place)))
● (def LOR (Where?. "Mordor"))
(deliver-dialogue LOR)
=> "One does not simply walk into Mordor"
Thank You :)

Weitere ähnliche Inhalte

Was ist angesagt?

JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 

Was ist angesagt? (20)

JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Javascript
JavascriptJavascript
Javascript
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Alpha beta pruning
Alpha beta pruningAlpha beta pruning
Alpha beta pruning
 
Inheritance and polymorphism
Inheritance and polymorphism   Inheritance and polymorphism
Inheritance and polymorphism
 
Regular Grammar
Regular GrammarRegular Grammar
Regular Grammar
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Automata theory
Automata theoryAutomata theory
Automata theory
 
Complexity of Algorithm
Complexity of AlgorithmComplexity of Algorithm
Complexity of Algorithm
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
 
OOPS In JAVA.pptx
OOPS In JAVA.pptxOOPS In JAVA.pptx
OOPS In JAVA.pptx
 
NP completeness
NP completenessNP completeness
NP completeness
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Top 50 HTML Interview Questions and Answers | Edureka
Top 50 HTML Interview Questions and Answers | EdurekaTop 50 HTML Interview Questions and Answers | Edureka
Top 50 HTML Interview Questions and Answers | Edureka
 

Ähnlich wie Clojure basics

Introduction to R
Introduction to RIntroduction to R
Introduction to R
agnonchik
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
A gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojureA gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojure
Paul Lam
 

Ähnlich wie Clojure basics (20)

Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
A gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojureA gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojure
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environment
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Do snow.rwn
Do snow.rwnDo snow.rwn
Do snow.rwn
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 
Pivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro Bignyak
 
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcional
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 

Mehr von Knoldus Inc.

Mehr von Knoldus Inc. (20)

Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Kürzlich hochgeladen (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Clojure basics

  • 1. Introduction to ClojureIntroduction to Clojure Sidharth Khattri Knoldus Software LLP Sidharth Khattri Knoldus Software LLP
  • 2. ● Clojure is a Functional Lisp (List Processing) which runs on JVM. ● It extends the principle of Code-as-Data system to include Maps and Vectors. Everything in clojure is written inside a data structure referred to as the S-expressions, i.e nested lists. Eg: (/ 4 (+ 1 2)) => ? ● Clojure is a Functional Lisp (List Processing) which runs on JVM. ● It extends the principle of Code-as-Data system to include Maps and Vectors. Everything in clojure is written inside a data structure referred to as the S-expressions, i.e nested lists. Eg: (/ 4 (+ 1 2)) => ? Function Name Arguments ● Every operation in clojure is done using a Post-Fix notation
  • 3. ● Experimenting with clojure is quite easy. In order to get started with clojure you need to follow the instructions on http://leiningen.org/ to set up clojure environment on your system. Leningen is used for project automation. ● Most popular IDE used for clojure is LightTable which can be download from http://www.lighttable.com/ ● You can fire up clojure's repl on linux terminal using: lein repl or you can directly use a Live REPL in LightTable. ● You can also use clojure in Eclipse using CounterClockwise plugin. ● Everything that you need to know about clojure can be found in the clojure cheatsheet at the following url: http://clojure.org/cheatsheet
  • 4. ● Even though a lot of parentheses can confuse programmers at first, LightTable(IDE) can make programming in clojure really easy. A sample of what usage of parentheses I'm talking about: (filter #(if(zero? (rem % 3)) true) (map #(+ % 1) (range 10))) => ? ● The above code in LightTable should look something like this: ● Last line of a function can return another function, i.e a Higher Order Function as illustrated in the following example: (defn attribute [who?] (if (= who? "superman") #(str "Superman " %) (fn[x] (str "Human " x)))) ((attribute "superman") "Flying") => "Superman Flying"
  • 5. (if 0 “Yee! True” “Huh! False”) => ? (if 1 “Yee! True” “Huh! False”) => ? Concept of truthy and falsy
  • 6. (if 0 “Yee! True” “Huh! False”) => “Yee! True” (if 1 “Yee! True” “Huh! False”) => “Yee! True” Concept of truthy and falsy
  • 7. Concept of truthy and falsy Everything in clojure is true except false or nil So, (if nil “Yee! True” “Huh! False”) => “Huh! False”
  • 8. Data Structures ● Clojure supports a number of data structures: Lists, Vectors, Maps, Sets ● All clojure data structures are persistent data structures. Internally they're implemented as a tree. ● Simplest way to define these data structures: '(1 2 3) defines a list [1 2 3] defines a vector #{1 2 3} defines a set {:1 “one” :2 “two”} defines a map
  • 9. Nesting ● Searching and updating nested structures is very easy. ● Searching: (def n {:india {:newdelhi {:knoldus {:address "30/29, 1st Floor, East Patel Nagar"}}} :usa {:california {:knoldus {:address "743, Catamaran Street "}}}}) user=> (get-in n [:india :newdelhi]) Returns {:knoldus {:address "30/29, 1st Floor, East Patel Nagar"}} ● Updating: (assoc-in n [:india :newdelhi :knoldus :number] 911142316525) Returns {:india {:newdelhi {:knoldus {:number 911142316525, :address "30/29, 1st Floor, East Patel Nagar"}}}, :usa {:california {:knoldus {:address "743, Catamaran Street "}}}} ● Remember that the value of “n” hasn't changed in any case.
  • 10. Threading Operators The previous code that we used: (filter #(if(zero? (rem % 3)) true) (map #(+ % 1) (range 10))) Is same as: (->> (range 10) (map #(+ % 1)) (filter #(if (zero? (rem % 3)) true))) The threaded version is much cleaner
  • 11. Threading Operators In Nested structures example that we used: (def n {:india {:newdelhi {:knoldus {:address "30/29, 1st Floor, East Patel Nagar"}}} :usa {:california {:knoldus {:address "743, Catamaran Street "}}}}) We can use: (-> n :india :newdelhi :knoldus :address) Instead of: (:address (:knoldus (:newdelhi (:india n))))
  • 12. Loops ● For loop: (for [x (range 1 10) :when (even? x)] x) => (2 4 6 8) ● While loop: (while 0 (println “hello”)) ● Loops with side effects: (dotimes [x 5] (print x)) => 01234nil (doseq [x [3 2 1]] (print x)) => 321nil
  • 13. Binding Form - let ● We use the “let” form to bind data structures to symbols. ● Example: (let [x 10 y 11 m (* x y)] m) user=> m
  • 14. Binding Form - let ● We can also use let binding for destructuring: ● (defn index-sum [v & i] (let [[x :as ind] (map #(get v %) i)] (reduce + ind))) (index-sum [1 2 3 4 5 6 7 8 9] 1 3 5) => ?
  • 15. Built-in Parallelism ● “map” function will take more time as compared to the “pmap” function: (time (doall (map (fn[x] (Thread/sleep 3000) (+ x 5)) (range 1 5)))) => "Elapsed time: 12000.99432 msecs" (6 7 8 9) (time (doall (pmap (fn[x] (Thread/sleep 3000) (+ x 5)) (range 1 5)))) => "Elapsed time: 3002.989534 msecs" (6 7 8 9)
  • 16. Futures ● Futures can be used to send any calculation intensive work in the background while continuing with some other work. ● Defining futures: (def f (future some-calculation-intensive-work)) ● Example: (defn show-result[] ;;do things (def f (future some-calculation-intensive-work)) ;;prepare gui to display result @f) ;;wait until the result is returned
  • 17. Atoms, refs and agents ● Atoms, refs and agents are the three options available for maintaining non- local mutable state in clojure ➔ Atoms are for Uncoordinated Synchronous access to a single Identity. ➔ Refs are for Coordinated Synchronous access to Many Identities. ➔ Agents are for Uncoordinated Asynchronous access to a single Identity.
  • 18. Atoms ● Defining an atom: (def a (atom {:a 1})) ● Getting the value stored in an atom: (deref a) or @a ● Changing the value of an atom: (swap! a #(assoc % :b 2)) => {:a 1 :b 2} or (reset! a 0) => Exception or changed value?
  • 19. Refs ● Defining refs: (def tasks-to-be-done (ref #{2 9 4})) (def tasks-done (ref #{1 3 5})) ● Coordinated change: (dosync (commute tasks-to-be-done disj 2) (commute tasks-done conj 2)) ● Accessing values of refs: @tasks-to-be-done => #{4 9} @tasks-to-be-done => #{1 2 3 5}
  • 20. Agents ● Can be useful in fork/join solutions. ● Defining an agent: (def a (agent 0)) ● Dispatching actions to an agent: (dotimes [x 3] (send-off a (fn[x] (Thread/sleep 3000) (inc x)))) @a => ? ● In case we want to wait until the above code snippet has finished processing, we can use: (await a)
  • 21. Arrays ● Defining an array: (def a1 (make-array Integer/TYPE 3)) (pprint a1) => [0, 0, 0] (def a2 (make-array Integer/TYPE 2 3)) (pprint a2) => [[0, 0, 0], [0, 0, 0]] ● (def a3 (to-array [1 2 3 4 5])) (pprint a3) => [1, 2, 3, 4, 5]
  • 22. Arrays ● Manipulating arrays: (def a1 (make-array Integer/TYPE 3)) (aset a1 1 10)) (pprint a1) => [0, 10, 0] (def a2 (make-array Integer/TYPE 2 3)) (aset (aget a2 0) 1 10) (pprint a2) => [[0, 10, 0], [0, 0, 0]]
  • 23. Datatypes ● defrecord creates an immutable persistent map (class-type datatype) (defrecord Hobbit [fname lname address]) (defrecord Address [street town city]) (def bb (Hobbit. "Bilbo" "Baggins" (Address. "Bagshot row" "Hobbiton" "Shire"))) ● user=> bb #user.Hobbit{:fname "Bilbo", :lname "Baggins", :address #user.Address{:street "Bagshot row", :town "Hobbiton", :city "Shire"}} ● (-> bb :address :city) “Shire”
  • 24. Datatypes ● deftype creates a bare-bones object (class-type datatype). Preferred for java inter operability. (deftype Hobbit [fname lname address]) (deftype Address [street town city]) (def bb (Hobbit. "Bilbo" "Baggins" (Address. "Bagshot row" "Hobbiton" "Shire"))) ● user=> bb #<Hobbit user.Hobbit@476c6b9c> ● (.street (.address bb)) "Bagshot row"
  • 25. Protocols ● Dataype are used to implement protocols or interfaces. (defprotocol Dialogue (deliver-dialogue [d])) (defrecord Where? [place] Dialogue (deliver-dialogue [d] (str "One does not simply walk into " place))) ● (def LOR (Where?. "Mordor")) (deliver-dialogue LOR) => "One does not simply walk into Mordor"