A taste of
!!
David Leung!!
Twitter: @davleung Email: [email protected]
GPG Fingerprint: 217E 1ECE 2349 D178 73E5 C194 1E2E C02A A74A A531
What is Clojure?
Hosted Excellent Interops
EXAMPLE 1 Retrieve a webpage using Java library !!;; Imports the java.net.URL class into current namespace (import ‘java.net.URL) ;; Creating an instance of URL. ;; In Java: ;; URL con = new URL(“http://www.reddit.com”) (def con (URL. “http://www.reddit.com”)) !!;; GET the page and print it! (println (slurp con))
What is Clojure?
Hosted Functional
First class functions
Build software by composing over functions
EXAMPLE 2 Applying arbitrary function to a collection of data
!;; Name a collection of numbers (def data [1 2 3 4 5]) !;; Creates a function called process-‐data that accepts a collection and an operation to be perofrmed on data (defn process-‐data [collection operation] (apply operation collection)) !;; Addition (process-‐data data +) !;; Multiplication (process-‐data data *) !
Relax if you aren’t following the syntax :-)
You’ll learn this in the workshop
What is Clojure?
Hosted Functional
Immutability
Easy Reasoning and Debugging
In the following Ruby code, can you be sure that x is not modified?
!x = {problems: 99} !dodgyMethod(x); !# what is the value of x? x[":problems"]
What is Clojure?
Hosted Functional
Immutability
Separation of Identity & State
!
Identity is a reference to something.
State is the aggregated values of an identity at a particular point in time.
In Clojure, an identity’s state is updated by creating a new value and assign it back to the identify.
!
Whaaaaat? Isn’t that inefficient???
What is Clojure?
Hosted Functional
Immutability
Efficient Structure Sharing !Let’s create a hash: !(def a {:a 5 :b 6 :c 7 :d 8}) !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Credit: Image from “Clojure Programming” by Chas Emerick, Brian Carper & Christophe Grand
What is Clojure?
Hosted Functional
Immutability
Efficient Structure Sharing !!(def a {:a 5 :b 6 :c 7 :d 8}) !(def b (assoc a :c 0)) !!!!!!!!!!!!!!!!!!
!
“Copying” data is cheap! !!!Credit: Image from “Clojure Programming” by Chas Emerick, Brian Carper & Christophe Grand
What is Clojure?
Hosted Functional
Immutability
Fosters Concurrent Programming
!“Immutable objects are always
thread safe.” —Brian Goetz
(Author of Java Concurrency in Practice) !
!!More about Concurrency later
What is Clojure?
Hosted Functional
Parallelism Parallel processing
Trivial Parallel Processing Problem
Problem The Boss just asked you to parse 100K serialized JSON objects into a hash. Each string is ~300KB.
The collection/array of strings are stored in the variable problemsCollection. !Write a snippet that makes use of all cores to process this collection. Don’t worry about storing the result. !Do this within a minute, or you are fired. !Time starts now.
What is Clojure?
Hosted Functional
Parallelism Parallel processing
Trivial Parallel Processing Problem
Solution
!!;; non-‐parallelized version that will get you fired (dorun (map json/read-‐str problemsCollection)) !;; parallelized version (dorun (pmap json/read-‐str problemsCollection)) !
!
EXAMPLE 3 (DEMO)
!
Note pmap is a parallelized version of map
What is Clojure?
Hosted Functional
Parallelism Parallel processing
Watch out for the overhead involved in distributing work to the work!
!
EXAMPLE 4 (DEMO)
!
What is Clojure?
Hosted Functional Parallelism
Concurrency Two types of
Concurrent Operations
Coordinated Concurrency
One or more actors (threads) must coordinate to produce the right computation.
e.g. Bank transactions
!
Synchronous Concurrency
Should the thread that wants to update a reference be blocked until their return?
What is Clojure?
Hosted Functional Parallelism
Concurrency 3 flavors of Reference
Types
Coordinated Uncoordinated
Synchronous Refs Atoms
Asynchronous Agents
What is Clojure?
Hosted Functional Parallelism
Concurrency Atoms
Create an atom
(def counter (atom 0))
Access an atom’s value (dereferencing)
(deref counter) !;; syntactical sugar @counter
Compare and Swap
(swap! counter + 2) !
Note: Clojure uses ! in a function’s name to denote that the function mutates state (memory/IO).
What is Clojure?
Hosted Functional Parallelism
Concurrency Software Transactional
Memory (STM)
STM: Database-like Transactions for Concurrency
!
Clojure controls updates to references via a system called STM. It removes the need for manual locking.
!
!
!
!
!
Fulfills the Atomicity, Consistency, and Isolation aspects of the Database Transaction Properties ACID.
STM is to concurrency what
Garbage Collector is to memory management
What is Clojure?
Hosted Functional Parallelism
Concurrency Software Transactional
Memory (STM)
There are more to concurrency
Clojure has “data flow variables” too!
We’ll cover concurrency in the workshops later. Things we will look at:
!
Future
Delay
Promise
What is Clojure?
Hosted Functional Parallelism
Concurrency Lisp
What is a Lisp?
!
!
!
!
!
!
Lisp is invented by John McCarthy in 1958.
Lisp pioneered ideas like tree data structures, dynamic typing, garbage collection, higher-order functions, recursion.
John McCarthy is quite the hero in Computer Science.
What is Clojure?
Hosted Functional Parallelism
Concurrency Lisp
Lisp: LISt Processing
Lisp is written in symbolic expressions, or S-expressions.
S-expressions are written as a pair of parenthesis surrounding a sequence of symbols:
(f a b c) !
The first position in the list is also known as the functional position. When evaluated, the function f will be called with the rest of the list as arguments.
What is Clojure?
Hosted Functional Parallelism
Concurrency Lisp
Collection Types
Collection types in Clojure
!
List (a b c d e) Essentially a linked list
Vector [a b c d e] Like “arrays” in Ruby/Python
!
Wait a second…
Didn’t we already see those square brackets and parentheses when we define a function?
What is Clojure?
Hosted Functional Parallelism
Concurrency Lisp
Homoiconicity
Homoiconicity
Lisp is a language where the structure of the code is represented by standard data structures (list, vectors, hash).
Repeat after me
!
Code as Data. Data as Code.
!
!(defn wont-‐make-‐you-‐blind [name] (println name ", parentheses won't make you blind"))
What is Clojure?
Hosted Functional Parallelism
Concurrency Lisp
Homoiconicity
Construct a function call with collection manipulation functions
!;; the quotation mark stops Clojure treating the ;; list as a function call (def arguments '(1 2 3)) !;; cons is a traditional lisp function ;; that prepends an object to the head of a list (def function-‐call (cons + arguments)) !(eval function-‐call) ;; => 6 !!
What is Clojure?
Hosted Functional Parallelism
Concurrency Lisp Macros
Building Malleable Systems
!
As well as being able to write code that “writes code” (metaprogramming), you can even change the evaluation semantics by writing macros!
We’ll explore this in the workshops.
What is Clojure?
Hosted Functional Parallelism
Concurrency Lisp
Language Extensions
The flexible of Clojure allows Clojure and your codebase to stretch and bend to your needs.
Notable Clojure extensions:
!
core.async Implementation of channels and blocks from the Go programming language.
core.logic Implementation of miniKanren for doing relational/constraint logic programming.
core.typed Optional typing for Clojure.
Working with Clojure
Build Tools !
Leiningen for automating Clojure projects without setting your hair on fire
http://leiningen.org !ht
Working with Clojure
Learning Resources
Test Driven Learning 4Clojure 4clojure.com Clojure Koans clojurekoans.com !Books Clojure Programming Joy of Clojure Second Edition Clojure Cookbook
Working with Clojure
!!
David Leung!!
Twitter: @davleung Email: [email protected]
GPG Fingerprint: 217E 1ECE 2349 D178 73E5 C194 1E2E C02A A74A A531