SlideShare una empresa de Scribd logo
1 de 52
Descargar para leer sin conexión
Clojure
for Java developers

jan.kronquist@jayway.com
About me

2012 2008 -& dynamic typing
- Lisp Functional
1997 68K assembly
1986 OOP
2005 1995 --Aspects, Mixins
1990IoC,University
- - - Basic
This talk is not
A comprehensive introduction to Clojure!
About idiomatic Clojure!
Another talk about functional programming
Killer apps
Prismatic!
Datomic!
Storm!
ClojureScript
What is Clojure?
Created 2007 by Rich Hickey!
Lisp!
Runs on JVM, CLR & JavaScript!
Design for concurrency
Clojure example
(defn divisible? [n d]	
(== 0 (mod n d)))	
!
(defn divides [n]	
(partial divisible? n))	
!
(declare primes)	
!
(defn prime? [n]	
(not (some (divides n) (take-while #(< % n) primes))))	
!
(def primes (lazy-cat	
[2 3 5]	
(filter prime? (drop 7 (range)))))
Why Clojure?
Lisp - Code as data & Syntactic abstraction!
Functional - Declarative, Immutable!
Interactive development environment!
Great eco-system!
Wrapper-free Java access
Common complaints
Dynamic typing is scary

Lisp looks weird
Just a toy language

Macros? Are you crazy?
Lispness
Clojure Atomic Data Types
Arbitrary precision integers: 12345678987654 !
Doubles: 1.234!
BigDecimals: 1.234M!
Ratios: 22/7!
Strings: "fred" , Characters: a b c !
Symbols: fred ethel , Keywords: :fred :ethel !
Booleans: true false , Null: - nil!
Regex patterns #"a*b"
Rich Hickey - Clojure for Java Programmers - http://www.youtube.com/watch?v=P76Vbsk_3J0
JavaScript Data Structures
Arrays!
[1, 2, 3]

["fred", "ethel", "lucy"]

Objects!
{name:

"Jan Kronquist", age: 37}
Clojure Data Structures
Vectors!
[1, 2, 3]

["fred", "ethel", "lucy"]

Maps!
{:name

"Jan Kronquist", :age 37}

move colon
Clojure Data Structures
Vectors!
[1 2 3]

["fred" "ethel" "lucy"]

Maps!
{:name

"Jan Kronquist" :age 37}

commas are whitespace!
Clojure Data Structures
Vectors - indexed access!
[1 2 3]

["fred" "ethel" "lucy"]

Maps!
{:name

"Jan Kronquist" :age 37}

Lists - singly linked!
(1 2 3 4 5) (fred ethel lucy) (list 1 2 3)

Sets !
#{fred ethel lucy}
Demo in REPL
user=> "hello"
"hello"
user=> 5
5
user=> [1 2 3]
[1 2 3]
user=> qwe
java.lang.RuntimeException: Unable to resolve symbol: qwe
!
user=> (def qwe "hello world")
#'user/qwe
user=> qwe
"hello world"
The strangeness of Lisp

println("Hello world")
(operator operand1 operand2 ...)
Determines how the list is evaluated
Example evaluation

(= (.toString (+ 1 2)) "3")
(= (.toString 3) "3")
(= "3" "3")
true
int i = 5;

(def i 5)

OR

(let [i 5] ...)

if (x > 5) {

return y;
} else {
return z;

}

(if (> x 5)

y
z)

x * y * z

(* x y z)

foo(x, y, z)

(foo x y z)

object.method(x, y)

(.method object x y)

public String sayHello(String x) {
return "Hello " + x;
}

(defn sayHello [x]
(str "Hello " x))
Java Quiz

	 public static void main(String[] args) {	
	 	 int bang = 1;	
do while (bang>=1)	
System.out.print(" bang is "+ bang);	
while (bang>1);	
	 }
Macros
Working with Java classes

static void display(String text) {	
	 JFrame frame = new JFrame("MyFrame");	
	 frame.add(new JLabel(text));	
	 frame.setSize(300, 200);	
	 frame.setVisible(true);	
}

(defn display [text]	
(let [frame (new JFrame "MyFrame")]	
(.add frame (new JLabel text))	
(.setSize frame 300 200)	
(.setVisible frame true)))

a pattern!

(display "Hello World")
Working with Java classes

static void display(String text) {	
	 JFrame frame = new JFrame("MyFrame");	
	 with (frame) {	
	 	 .add(new JLabel(text));	
	 	 .setSize(300, 200);	
	 	 .setVisible(true);	
	 }	
}

(defn display [text]	
(let [frame (new JFrame "MyFrame")]	
(.add frame (new JLabel text))	
(.setSize frame 300 200)	
(.setVisible frame true)))
Working with Java classes

static void display(String text) {	
	 JFrame frame = new JFrame("MyFrame");	
	 with (frame) {	
	 	 .add(new JLabel(text));	
	 	 .setSize(300, 200);	
	 	 .setVisible(true);	
	 }	
}

(defn display [text]	
(let [frame (new JFrame "MyFrame")]	
(doto frame	
(.add (new JLabel text))	
(.setSize 300 200)	
(.setVisible true))))
Working with Java classes

static void display(String text) {	
	 JFrame frame = new JFrame("MyFrame");	
	 frame.add(new JLabel(text));	
	 frame.setSize(300, 200);	
	 frame.setVisible(true);	
}

(defn display [text]	
(doto (new JFrame "MyFrame")	
(.add (new JLabel text))	
(.setSize 300 200)	
(.setVisible true)))	

Ok, nice, 	

but in practice you would 	

never want something like this?
Trust me, you want macros

static void write(String fileName, String text) throws IOException {	
	 try (Writer writer = new FileWriter(fileName)) {	
	 	 writer.write(text);	
	 }	
}

(defn write [fileName text]	
(with-open [writer (new FileWriter fileName)]	
(.write writer text)))
Toy?
Structure in
Modules - package!
Abstraction - interface!
Implementation - class!
!

Problems!
mutable state?!
static methods?!
inheritance?!
constants?
Structure in
Modules!
namespace - first-class, dynamic, import, aliasing!

Abstraction !
defprotocol - can be added later!

Implementation!
defrecord - immutable, equals, hashcode, etc!
deftype - may mutate, only user functionilty!
reify - singleton!
gen-class & proxy - for Java interop
Records - creating
(ns my.namespace)	
(defrecord Person [firstName lastName])	
(new Person "Jan" "Kronquist")
; #my.namespace.Person{:firstName "Jan", :lastName "Kronquist"}
Records - field access
(ns my.namespace)	
(defrecord Person [firstName lastName])	
(new Person "Jan" "Kronquist")
; #my.namespace.Person{:firstName "Jan", :lastName "Kronquist"}
(def person (new Person "Jan" "Kronquist"))	
(.firstName person)
; "Jan"
Records - named parameters
(ns my.namespace)	
(defrecord Person [firstName lastName])	
(new Person "Jan" "Kronquist")
; #my.namespace.Person{:firstName "Jan", :lastName "Kronquist"}
(def person (new Person "Jan" "Kronquist"))	
(.firstName person)
; "Jan"
(map->Person {:lastName "Kronquist" :firstName "Jan"})
; #my.namespace.Person{:firstName "Jan", :lastName "Kronquist"}
Records and protocols
(defprotocol Nameable	
(getName [this]))

Person class

implements
Nameable interface

(defrecord Person [firstName lastName]	
Nameable	
(getName [this] (str firstName " " lastName)))	

!
(getName (new Person "Jan" "Kronquist"))	

!
; "Jan Kronquist"

Person
Nameable

extended by
after definition!

(defrecord Person [firstName lastName])	

!
(extend-protocol Nameable	
Person	
(getName [this] (str (.firstName this) " " (.lastName this))))	

!
(getName (new Person "Jan" "Kronquist"))	

!
; "Jan Kronquist"
Records and protocols
(defprotocol Nameable	
(getName [this]))

(defrecord Person [firstName lastName]	
Nameable	
(getName [this] (str firstName " " lastName)))	

Method getName 	
exists on Person class

!
(.getName (new Person "Jan" "Kronquist"))	

!
; "Jan Kronquist"

(defrecord Person [firstName lastName])	

!
(extend-protocol Nameable	
Person	
(getName [this] (str (.firstName this) " " (.lastName this))))	

!
(getName (new Person "Jan" "Kronquist"))	

!
; "Jan Kronquist"
Records and protocols
(defprotocol Nameable	
(getName [this]))

(defrecord Person [firstName lastName]	
Nameable	
(getName [this] (str firstName " " lastName)))	

Method getName 	
exists on Person class

!
(.getName (new Person "Jan" "Kronquist"))	

!
; "Jan Kronquist"

(defrecord Person [firstName lastName])	

!

But not in this case!

(extend-protocol Nameable	
Person	
(getName [this] (str (.firstName this) " " (.lastName this))))	

!
(.getName (new Person "Jan" "Kronquist"))	

!
; IllegalArgumentException No matching field found: getName
Editors and IDEs?
Eclipse - Counterclockwise!
IntelliJ - La Clojure!
Light Table!
Sublime!
Textmate!
Emacs
Eclipse Counterclockwise

https://code.google.com/p/counterclockwise/

✓Restrictive formatting!

✓Typing suggestions!

✓Paren coloring!

✓Being Eclipse
Light table

http://www.lighttable.com/

✓Cool!

✓Insta-REPL
Sublime

http://www.sublimetext.com/

✓General purpose editor!
✓Typing suggestions
Repositories
Maven style!
Maven central!
http://clojars.org/repo
Build tools
Maven plugin!
Gradle plugin!
Leiningen
Leiningen

(defproject myproject "0.5.0-SNAPSHOT"!
:description "A project for doing things."!
:url "http://github.com/foo/bar"!
:dependencies [[org.clojure/clojure "1.5.1"]!
[ring/ring-core "1.2.0 "]]!
:plugins [[lein-ring "0.4.5"]])
Dynamic typing
Dynamic typing?

Robert Smallshire - The Unreasonable Effectiveness of Dynamic Typing for Practical Programs
Dynamic typing is scary
Compiler won’t find errors!
Limited tool support!
Performance?
What made me think twice

Web server
Clojure makes dynamic typing ok
REPL!
Immutable data structure !
Pure functions!
Automated tests
Studies
Stefan Hanenberg & Lutz Prechelt!
Dynamic is more productive!
No difference in reliability!

Robert Smallshire - 2 % defects are type errors (GitHub)
Still not convinced?
Clojure is compiled to bytecode!
Type hints!

(defn len [^String x]	
(.length x))

!

core.typed

(t/ann f [Integer -> Integer])	
(defn f [x] (int (inc x)))
Conclusion
Convinced?

REPL!
Immutable data structure !
Pure functions!
Automated tests

Dynamic typing is scary
usable
(operation operand1 operand2 ...)

Lisp looks weird
is consistent
Namespaces!
Prototcols!
Records

Interesting language
Just a toy
Lazy seqs!

STM!

Functional

try (Writer writer = new FileWriter(fileName)) {	
	
writer.write(text);	
}

Macros? Are you crazy?
Maybe.......
DSL!

Reuse!

Structure
Further resources
http://clojure.org/!
http://tryclj.com/!
http://www.4clojure.com!
http://clojure-doc.org/
Questions?

Más contenido relacionado

La actualidad más candente

Predictably
PredictablyPredictably
Predictably
ztellman
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC
 
The Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unificationThe Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unification
Norman Richards
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
Kiyotaka Oku
 

La actualidad más candente (20)

Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Predictably
PredictablyPredictably
Predictably
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in Groovy
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talk
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
The Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unificationThe Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unification
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matter
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 

Destacado

Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmers
elliando dias
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmers
elliando dias
 
31 η ανάκτηση της πόλης από τον μιχ. παλαιολόγο
31 η ανάκτηση της πόλης από τον μιχ. παλαιολόγο31 η ανάκτηση της πόλης από τον μιχ. παλαιολόγο
31 η ανάκτηση της πόλης από τον μιχ. παλαιολόγο
george papadopoulos
 

Destacado (14)

Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmers
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmers
 
Trinity Kings World Leadership: Family Franchise Systems:The President, The S...
Trinity Kings World Leadership: Family Franchise Systems:The President, The S...Trinity Kings World Leadership: Family Franchise Systems:The President, The S...
Trinity Kings World Leadership: Family Franchise Systems:The President, The S...
 
Madagascar
MadagascarMadagascar
Madagascar
 
Vietnam´s Unseen War (Pictures from the other side)
Vietnam´s Unseen War (Pictures from the other side)Vietnam´s Unseen War (Pictures from the other side)
Vietnam´s Unseen War (Pictures from the other side)
 
Costs of Closed Science
Costs of Closed ScienceCosts of Closed Science
Costs of Closed Science
 
Trinity Kings Family Archives part 2 (revised)
Trinity Kings Family Archives part 2  (revised)Trinity Kings Family Archives part 2  (revised)
Trinity Kings Family Archives part 2 (revised)
 
Trinity Kings World Leadership: Family Franchising Systems: Pittsburgh PA id ...
Trinity Kings World Leadership: Family Franchising Systems: Pittsburgh PA id ...Trinity Kings World Leadership: Family Franchising Systems: Pittsburgh PA id ...
Trinity Kings World Leadership: Family Franchising Systems: Pittsburgh PA id ...
 
The periodic table by Muhammad Fahad Ansari 12IEEM14
The periodic table by Muhammad Fahad Ansari 12IEEM14 The periodic table by Muhammad Fahad Ansari 12IEEM14
The periodic table by Muhammad Fahad Ansari 12IEEM14
 
Trinity Kings World Leadership: "Ambassador of Leadership for the World" *Fin...
Trinity Kings World Leadership: "Ambassador of Leadership for the World" *Fin...Trinity Kings World Leadership: "Ambassador of Leadership for the World" *Fin...
Trinity Kings World Leadership: "Ambassador of Leadership for the World" *Fin...
 
To All My Dear Friends...
To All My Dear Friends...To All My Dear Friends...
To All My Dear Friends...
 
Supply of water resources by Muhammad Fahad Ansari 12IEEM14
Supply of water resources by Muhammad Fahad Ansari 12IEEM14Supply of water resources by Muhammad Fahad Ansari 12IEEM14
Supply of water resources by Muhammad Fahad Ansari 12IEEM14
 
Patillo family
Patillo familyPatillo family
Patillo family
 
31 η ανάκτηση της πόλης από τον μιχ. παλαιολόγο
31 η ανάκτηση της πόλης από τον μιχ. παλαιολόγο31 η ανάκτηση της πόλης από τον μιχ. παλαιολόγο
31 η ανάκτηση της πόλης από τον μιχ. παλαιολόγο
 

Similar a Clojure for Java developers - Stockholm

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
Garth Gilmour
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
univalence
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
On Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian PerspectiveOn Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian Perspective
looselytyped
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
dico_leque
 

Similar a Clojure for Java developers - Stockholm (20)

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
(first '(Clojure.))
(first '(Clojure.))(first '(Clojure.))
(first '(Clojure.))
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Clojure入門
Clojure入門Clojure入門
Clojure入門
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
 
Scala
ScalaScala
Scala
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lisp
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
On Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian PerspectiveOn Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian Perspective
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
 
Groovy
GroovyGroovy
Groovy
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Clojure for Java developers - Stockholm

  • 2. About me 2012 2008 -& dynamic typing - Lisp Functional 1997 68K assembly 1986 OOP 2005 1995 --Aspects, Mixins 1990IoC,University - - - Basic
  • 3. This talk is not A comprehensive introduction to Clojure! About idiomatic Clojure! Another talk about functional programming
  • 5. What is Clojure? Created 2007 by Rich Hickey! Lisp! Runs on JVM, CLR & JavaScript! Design for concurrency
  • 6. Clojure example (defn divisible? [n d] (== 0 (mod n d))) ! (defn divides [n] (partial divisible? n)) ! (declare primes) ! (defn prime? [n] (not (some (divides n) (take-while #(< % n) primes)))) ! (def primes (lazy-cat [2 3 5] (filter prime? (drop 7 (range)))))
  • 7. Why Clojure? Lisp - Code as data & Syntactic abstraction! Functional - Declarative, Immutable! Interactive development environment! Great eco-system! Wrapper-free Java access
  • 8. Common complaints Dynamic typing is scary Lisp looks weird Just a toy language Macros? Are you crazy?
  • 10. Clojure Atomic Data Types Arbitrary precision integers: 12345678987654 ! Doubles: 1.234! BigDecimals: 1.234M! Ratios: 22/7! Strings: "fred" , Characters: a b c ! Symbols: fred ethel , Keywords: :fred :ethel ! Booleans: true false , Null: - nil! Regex patterns #"a*b" Rich Hickey - Clojure for Java Programmers - http://www.youtube.com/watch?v=P76Vbsk_3J0
  • 11. JavaScript Data Structures Arrays! [1, 2, 3] ["fred", "ethel", "lucy"] Objects! {name: "Jan Kronquist", age: 37}
  • 12. Clojure Data Structures Vectors! [1, 2, 3] ["fred", "ethel", "lucy"] Maps! {:name "Jan Kronquist", :age 37} move colon
  • 13. Clojure Data Structures Vectors! [1 2 3] ["fred" "ethel" "lucy"] Maps! {:name "Jan Kronquist" :age 37} commas are whitespace!
  • 14. Clojure Data Structures Vectors - indexed access! [1 2 3] ["fred" "ethel" "lucy"] Maps! {:name "Jan Kronquist" :age 37} Lists - singly linked! (1 2 3 4 5) (fred ethel lucy) (list 1 2 3) Sets ! #{fred ethel lucy}
  • 15. Demo in REPL user=> "hello" "hello" user=> 5 5 user=> [1 2 3] [1 2 3] user=> qwe java.lang.RuntimeException: Unable to resolve symbol: qwe ! user=> (def qwe "hello world") #'user/qwe user=> qwe "hello world"
  • 16. The strangeness of Lisp println("Hello world") (operator operand1 operand2 ...) Determines how the list is evaluated
  • 17. Example evaluation (= (.toString (+ 1 2)) "3") (= (.toString 3) "3") (= "3" "3") true
  • 18. int i = 5; (def i 5) OR (let [i 5] ...) if (x > 5) {
 return y; } else { return z;
 } (if (> x 5)
 y z) x * y * z (* x y z) foo(x, y, z) (foo x y z) object.method(x, y) (.method object x y) public String sayHello(String x) { return "Hello " + x; } (defn sayHello [x] (str "Hello " x))
  • 19. Java Quiz public static void main(String[] args) { int bang = 1; do while (bang>=1) System.out.print(" bang is "+ bang); while (bang>1); }
  • 21. Working with Java classes static void display(String text) { JFrame frame = new JFrame("MyFrame"); frame.add(new JLabel(text)); frame.setSize(300, 200); frame.setVisible(true); } (defn display [text] (let [frame (new JFrame "MyFrame")] (.add frame (new JLabel text)) (.setSize frame 300 200) (.setVisible frame true))) a pattern! (display "Hello World")
  • 22. Working with Java classes static void display(String text) { JFrame frame = new JFrame("MyFrame"); with (frame) { .add(new JLabel(text)); .setSize(300, 200); .setVisible(true); } } (defn display [text] (let [frame (new JFrame "MyFrame")] (.add frame (new JLabel text)) (.setSize frame 300 200) (.setVisible frame true)))
  • 23. Working with Java classes static void display(String text) { JFrame frame = new JFrame("MyFrame"); with (frame) { .add(new JLabel(text)); .setSize(300, 200); .setVisible(true); } } (defn display [text] (let [frame (new JFrame "MyFrame")] (doto frame (.add (new JLabel text)) (.setSize 300 200) (.setVisible true))))
  • 24. Working with Java classes static void display(String text) { JFrame frame = new JFrame("MyFrame"); frame.add(new JLabel(text)); frame.setSize(300, 200); frame.setVisible(true); } (defn display [text] (doto (new JFrame "MyFrame") (.add (new JLabel text)) (.setSize 300 200) (.setVisible true))) Ok, nice, but in practice you would never want something like this?
  • 25. Trust me, you want macros static void write(String fileName, String text) throws IOException { try (Writer writer = new FileWriter(fileName)) { writer.write(text); } } (defn write [fileName text] (with-open [writer (new FileWriter fileName)] (.write writer text)))
  • 26. Toy?
  • 27. Structure in Modules - package! Abstraction - interface! Implementation - class! ! Problems! mutable state?! static methods?! inheritance?! constants?
  • 28. Structure in Modules! namespace - first-class, dynamic, import, aliasing! Abstraction ! defprotocol - can be added later! Implementation! defrecord - immutable, equals, hashcode, etc! deftype - may mutate, only user functionilty! reify - singleton! gen-class & proxy - for Java interop
  • 29. Records - creating (ns my.namespace) (defrecord Person [firstName lastName]) (new Person "Jan" "Kronquist") ; #my.namespace.Person{:firstName "Jan", :lastName "Kronquist"}
  • 30. Records - field access (ns my.namespace) (defrecord Person [firstName lastName]) (new Person "Jan" "Kronquist") ; #my.namespace.Person{:firstName "Jan", :lastName "Kronquist"} (def person (new Person "Jan" "Kronquist")) (.firstName person) ; "Jan"
  • 31. Records - named parameters (ns my.namespace) (defrecord Person [firstName lastName]) (new Person "Jan" "Kronquist") ; #my.namespace.Person{:firstName "Jan", :lastName "Kronquist"} (def person (new Person "Jan" "Kronquist")) (.firstName person) ; "Jan" (map->Person {:lastName "Kronquist" :firstName "Jan"}) ; #my.namespace.Person{:firstName "Jan", :lastName "Kronquist"}
  • 32. Records and protocols (defprotocol Nameable (getName [this])) Person class implements Nameable interface (defrecord Person [firstName lastName] Nameable (getName [this] (str firstName " " lastName))) ! (getName (new Person "Jan" "Kronquist")) ! ; "Jan Kronquist" Person Nameable extended by after definition! (defrecord Person [firstName lastName]) ! (extend-protocol Nameable Person (getName [this] (str (.firstName this) " " (.lastName this)))) ! (getName (new Person "Jan" "Kronquist")) ! ; "Jan Kronquist"
  • 33. Records and protocols (defprotocol Nameable (getName [this])) (defrecord Person [firstName lastName] Nameable (getName [this] (str firstName " " lastName))) Method getName exists on Person class ! (.getName (new Person "Jan" "Kronquist")) ! ; "Jan Kronquist" (defrecord Person [firstName lastName]) ! (extend-protocol Nameable Person (getName [this] (str (.firstName this) " " (.lastName this)))) ! (getName (new Person "Jan" "Kronquist")) ! ; "Jan Kronquist"
  • 34. Records and protocols (defprotocol Nameable (getName [this])) (defrecord Person [firstName lastName] Nameable (getName [this] (str firstName " " lastName))) Method getName exists on Person class ! (.getName (new Person "Jan" "Kronquist")) ! ; "Jan Kronquist" (defrecord Person [firstName lastName]) ! But not in this case! (extend-protocol Nameable Person (getName [this] (str (.firstName this) " " (.lastName this)))) ! (.getName (new Person "Jan" "Kronquist")) ! ; IllegalArgumentException No matching field found: getName
  • 35. Editors and IDEs? Eclipse - Counterclockwise! IntelliJ - La Clojure! Light Table! Sublime! Textmate! Emacs
  • 40. Build tools Maven plugin! Gradle plugin! Leiningen
  • 41. Leiningen (defproject myproject "0.5.0-SNAPSHOT"! :description "A project for doing things."! :url "http://github.com/foo/bar"! :dependencies [[org.clojure/clojure "1.5.1"]! [ring/ring-core "1.2.0 "]]! :plugins [[lein-ring "0.4.5"]])
  • 43. Dynamic typing? Robert Smallshire - The Unreasonable Effectiveness of Dynamic Typing for Practical Programs
  • 44. Dynamic typing is scary Compiler won’t find errors! Limited tool support! Performance?
  • 45. What made me think twice Web server
  • 46. Clojure makes dynamic typing ok REPL! Immutable data structure ! Pure functions! Automated tests
  • 47. Studies Stefan Hanenberg & Lutz Prechelt! Dynamic is more productive! No difference in reliability! Robert Smallshire - 2 % defects are type errors (GitHub)
  • 48. Still not convinced? Clojure is compiled to bytecode! Type hints! (defn len [^String x] (.length x)) ! core.typed (t/ann f [Integer -> Integer]) (defn f [x] (int (inc x)))
  • 50. Convinced? REPL! Immutable data structure ! Pure functions! Automated tests Dynamic typing is scary usable (operation operand1 operand2 ...) Lisp looks weird is consistent Namespaces! Prototcols! Records Interesting language Just a toy Lazy seqs! STM! Functional try (Writer writer = new FileWriter(fileName)) { writer.write(text); } Macros? Are you crazy? Maybe....... DSL! Reuse! Structure