SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
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 :)

Más contenido relacionado

La actualidad más candente

Adjustment of inheritance
Adjustment of inheritanceAdjustment of inheritance
Adjustment of inheritanceSadhana28
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work pptRanjith Alappadan
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keywordtanu_jaswal
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introductionBhagath Gopinath
 
INTRODUCTION TO ALGORITHMS Third Edition
INTRODUCTION TO ALGORITHMS Third EditionINTRODUCTION TO ALGORITHMS Third Edition
INTRODUCTION TO ALGORITHMS Third EditionPHI Learning Pvt. Ltd.
 
Presentation on Heap Sort
Presentation on Heap Sort Presentation on Heap Sort
Presentation on Heap Sort Amit Kundu
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
 
Java. Инкапсуляция.
Java. Инкапсуляция.Java. Инкапсуляция.
Java. Инкапсуляция.Unguryan Vitaliy
 

La actualidad más candente (20)

Adjustment of inheritance
Adjustment of inheritanceAdjustment of inheritance
Adjustment of inheritance
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java Beans
Java BeansJava Beans
Java Beans
 
Java operators
Java operatorsJava operators
Java operators
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
C# Access modifiers
C# Access modifiersC# Access modifiers
C# Access modifiers
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
 
INTRODUCTION TO ALGORITHMS Third Edition
INTRODUCTION TO ALGORITHMS Third EditionINTRODUCTION TO ALGORITHMS Third Edition
INTRODUCTION TO ALGORITHMS Third Edition
 
Presentation on Heap Sort
Presentation on Heap Sort Presentation on Heap Sort
Presentation on Heap Sort
 
Query optimization
Query optimizationQuery optimization
Query optimization
 
Binary Search
Binary SearchBinary Search
Binary Search
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
Lesson 6 php if...else...elseif statements
Lesson 6   php if...else...elseif statementsLesson 6   php if...else...elseif statements
Lesson 6 php if...else...elseif statements
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Java. Инкапсуляция.
Java. Инкапсуляция.Java. Инкапсуляция.
Java. Инкапсуляция.
 

Similar 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
 

Similar 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
 

Más de Knoldus 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.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxKnoldus Inc.
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance TestingKnoldus Inc.
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxKnoldus Inc.
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationKnoldus Inc.
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 

Más de Knoldus Inc. (20)

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
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptx
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance Testing
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptx
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower Presentation
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 

Último

An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPCeline George
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...HetalPathak10
 

Último (20)

Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERP
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Chi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical VariableChi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical Variable
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptx
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
 

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"