SlideShare uma empresa Scribd logo
1 de 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 :)

Mais conteúdo relacionado

Mais procurados

Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in javasharma230399
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
Properties and indexers in C#
Properties and indexers in C#Properties and indexers in C#
Properties and indexers in C#Hemant Chetwani
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
Lecture 2 more about parallel computing
Lecture 2   more about parallel computingLecture 2   more about parallel computing
Lecture 2 more about parallel computingVajira Thambawita
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
 
Event handling
Event handlingEvent handling
Event handlingswapnac12
 

Mais procurados (20)

Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handler
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Js ppt
Js pptJs ppt
Js ppt
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Properties and indexers in C#
Properties and indexers in C#Properties and indexers in C#
Properties and indexers in C#
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Lecture 2 more about parallel computing
Lecture 2   more about parallel computingLecture 2   more about parallel computing
Lecture 2 more about parallel computing
 
jQuery
jQueryjQuery
jQuery
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
Event handling
Event handlingEvent handling
Event handling
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 

Semelhante a Clojure basics

Introduction to R
Introduction to RIntroduction to R
Introduction to Ragnonchik
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingMichael Arenzon
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry 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 clojurePaul Lam
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in rmanikanta361
 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environmentYogendra Chaubey
 
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 212Mahmoud Samir Fayed
 
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 2015Michiel Borkent
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schoolsDan Bowen
 
Do snow.rwn
Do snow.rwnDo snow.rwn
Do snow.rwnARUN DN
 
Pivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak MeetUp
 
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcionaltdc-globalcode
 

Semelhante a 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
 

Mais de Knoldus Inc.

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxKnoldus Inc.
 
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 ParsingKnoldus Inc.
 
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 IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
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.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
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 TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
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 PresentationKnoldus Inc.
 
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 APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 

Mais de Knoldus Inc. (20)

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
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 

Último (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

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"