Clojure for Java developers

Preview:

Citation preview

Clojure for

Java developers

Assumptions

Some experience with Java development

Little or no experience with Clojure

You want to try something different!

Haskell, Erlang and

Scala seem hairy!

Why Clojure ?

Why get functional ?

4 cores in a typical developers Mac book Pro

How long until 128 cores in a laptop is common?

Parallelism made simpler

Provides tools to create massively parallel applications

Not a panacea

Think differently

Functional concepts

Changing state

What is Clojure

One of many JVM languages

JavaGroovyJRubyJythonScala

ClojureJaskell

Erjalang

A little more ubiquitous

.Net framework – DLR/CLR

In browsers > ClojureScript

Native compilers

Very small syntax

( )[ ], { }

def, defn, defproject list, map, vector, set

let._

atom

Mathematical concepts

Functions have a value

For a given set of arguments, you should always get the same

result(Referential transparency)

Clojure concepts

Encourages Pure Functional approach

- use STM to change state

Functions as first class citizens

- functions as arguments as they return a value

Make JVM interoperation simple

- easy to use your existing Java applications

A better Lisp !

Sensible () usage

Sensible macro names

JVM Interoperability

Lisp is the 2nd oldest programming language still in use

Which LISP is your wingman ?Common Lisp Clojure

Clojure is modular

Comparing Clojurewith Java

The dark side of Clojure

( x )( x )

The dark side of Clojure

( ( x ) )( ( x ) )

The dark side of Clojure

( ( ( x ) ) )( ( ( x ) ) )

The dark side of Clojure

( ( ( ( x ) ) ) )( ( ( ( x ) ) ) )

The dark side of Clojure

( ( ( ( ( x ) ) ) ) )( ( ( ( ( x ) ) ) ) )

() verses

{ () };

Clojure verses Java syntax

([] (([]))) verses

{ ({([])}) };

Well actually more like....

Its all byte code in the end..

Any object in Clojure is just a regular java object

Types inherit from:

java.lang.object

What class is that...

(class "Jr0cket")

=> java.lang.String

(class

(defn hello-world [name]

(str "Hello cruel world")))

=> clojure.lang.Var

Using (type …) you can discover either the metadata or class of something

Prefix notation

3 + 4 + 5 – 6 / 3

(+ 3 4 5 (- (/ 6 3)))

Java made simpler

// Java

import java.util.Date;{

Date currentDate = new Date();

}

; Clojure

(import java.util.Date)

(new Date)

Ratio

Unique data type

Allow lazy evaluation

Avoid loss of precision

(/ 2 4)

(/ 2.0 4)

(/ 1 3)

(/ 1.0 3)

(class (/ 1 3)

Prefix notation everywhere

(defn square-the-number [x]

(* x x))

Defining a data structure

( def my-data-structure [ data ] )

( def days-of-the-week

[“Monday” “Tuesday” “Wednesday”])

You can dynamically redefine what the name binds to, but the vector is immutable

Really simple data structure

(def jr0cket

{:first-name "John",

:last-name "Stevenson"})

Using a map to hold key-value pairs.

A good way to group data into a meaningful concept

Defining simple data

(def name data)

Calling Behaviour

(function-name data data)

Immutable Data structures

List – Ordered collection

(list 1 3 5 7)

'(1 3 5 7)

(quote (1 3 5 7))

(1 2 3) ; 1 is not a function

Vectors – hashed ordered list

[:matrix-characters

[:neo :morpheus :trinity :smith]]

(first

[:neo :morpheus :trinity :smith])

(nth

[:matrix :babylon5 :firefly] 2)

(concat [:neo] [:trinity])

Maps – unordered key/values

{:a 1 :b 2}

{:a 1, :b 2}

{ :a 1 :b }java.lang.ArrayIndexOutOfBoundsException: 3

{ :a 1 :b 2}

{:a 1, :b 2}

{:a {:a 1}}

{:a {:a 1}}

{{:a 1} :a}

{{:a 1} :a}; idiom - put :a on the left

Lists are for codeand data

Vectors are for data and arguments

Its not that black and white, but its a useful starting point when learning

Interacting With Java

Joda Time(use 'clj-time.core)

(date-time 1986 10 14)

(hour (date-time 1986 10 14 22))

(from-time-zone (date-time 2012 10 17)

(time-zone-for-offset -8))

(after? (date-time 1986 10)

(date-time 1986 9))

(show-formatters)

Importing Java into Clojure

(ns drawing-demo

(:import [javax.swing Jpanel JFrame]

[java.awt Dimension]))

Calling Java GUI

(javax.swing.JOptionPane/showMessageDialog nil "Hello Java Developers" )

do makes swing easy

Simplifying with doto

doto evaluates the first expression in a chain of expressions and saves it in a temporary variable. It then inserts that variable as the first argument in each of the following expressions. Finally, doto returns the value of the temporary variable.

Working with Java

Java Classes ● fullstop after class name

(JFrame. )

(Math/cos 3) ; static method call

Java methods● fullstop before method name

(.getContentPane frame) ;;method name first

(. frame getContentPane) ;;object first

Get coding !

clojure.org

docs.clojure.org

All hail the REPLAn interactive shell for clojure

Fast feedback loop for clojure

Managing a Clojure project

Maven

Just like any other Java project

Step 1)

Add Clojure library dependency to your POM

Step 2)

Download the Internet !!!

Leiningen

lein new

lein deps

lein repl

lein jack-in

● Create a new Clojure project● Download all dependencies● Start the interactive shell (repl)● Start a REPL server

leiningen.org

Eclipse & Clojure = Counter Clockwise

Emacs

Light table

Kickstarter project to build a development environment, focused on the developer experience

Functional Web

webnoir.org

Clojure calling Java web stuff

(let [conn]

(doto (HttpUrlConnection. Url)

(.setRequestMethod “POST”)

(.setDoOutput true)

(.setInstaneFollowRedirects true))])

Deploy Clojure to the Cloud

lein new heroku my-web-app

Getting a little more functional

Recursive functions

● Functions that call themselves

● Fractal coding

● Tail recursion● Avoids blowing the

stack

● A trick as the JVM does not support tail recursion directly :-(

Recursion – managing memory

(defn recursive-counter [value]

(print value)

(if (< value 1000)

(recur (+ value 4))))

(recursive-counter 100)

Mutable State

Software Transactional MemoryProvides safe, concurrent access to memory

Agents allow encapsulated access to mutable resources

http://www.studiotonne.com/illustration/software-transactional-memory/

Atoms - Coding state changes

; Clojure atom code

(def mouseposition (atom [0 0]))

(let [[mx my] @mouseposition])

(reset! mouseposition [x y])

Database access

Clojure-contrib has sql library

Korma - "Tasty SQL for Clojure"

CongoMongo for MongoDB

https://devcenter.heroku.com/articles/clojure-web-application

Getting Creative with Clojure

Overtone: Music to your ears

Where to find out more...

clojure.org/cheatsheet

Hacking Clojure challenges

Thank you

@jr0cket

London ClojuriansGoogle Group

Recommended