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

Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Predictably
PredictablyPredictably
Predictablyztellman
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in GroovyJim Driscoll
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
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 2019Leonardo Borges
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talkJohn Stevenson
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of androidDJ Rausch
 
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 unificationNorman Richards
 
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 TestHoward Lewis Ship
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GParsPaul King
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Kiyotaka Oku
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMsunng87
 
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 languagePawel Szulc
 
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 matterDawid Weiss
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 

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 Programmerselliando dias
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmerselliando dias
 
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...Terrell Patillo
 
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)Cachi Chien
 
Costs of Closed Science
Costs of Closed ScienceCosts of Closed Science
Costs of Closed ScienceJohann Höchtl
 
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)Terrell Patillo
 
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 ...Terrell Patillo
 
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 fahadansari131
 
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...Terrell Patillo
 
To All My Dear Friends...
To All My Dear Friends...To All My Dear Friends...
To All My Dear Friends...Cachi Chien
 
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 12IEEM14fahadansari131
 
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 ProgrammingGarth Gilmour
 
(first '(Clojure.))
(first '(Clojure.))(first '(Clojure.))
(first '(Clojure.))niklal
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
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 streamRuslan Shevchenko
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macrosunivalence
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
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)Phil Calçado
 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lispkyleburton
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)Jacek Laskowski
 
On Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian PerspectiveOn Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian Perspectivelooselytyped
 
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 Wsloffenauer
 
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 ...PROIDEA
 
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

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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 FresherRemote DBA Services
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Último (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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