Introduction to Clojure Programming Silicon Valley Code Camp October 8th, 2011 Abbas Raza
Myself user => (def speaker { :name “Abbas Raza” :company “SuccessFactors” :team “Platform Engineering” :twitter “theceo”})
Clojure Foundation Getting Started Building Blocks
Advanced Topics Comparing Languages Comparing Paradigms
Thanks! Rich Hickey Clojure Creator
What is Clojure General Purpose Language Dynamic Functional Lisp Strengths Java/CLR/Javascript
Clojure - Timeline First released October 16, 2007 1.0 released 05/04/09 1.1 released 12/31/09 1.2 released 08/19/10 1.3 released 09/23/11 ClojureScript released July, 2011
Who’s using Clojure? http://dev.clojure.org/display/community/Clojure+Success+Stories
Functional Programming
H/W Perf Free Lunch is over http://www.gotw.ca/publications/concurrency-ddj.htm
Functional Programming No side effects – immutable Functions are first class citizens Functions passed in as parameters Functions return functions Functions can be created at runtime
Software Transactional Memory Provides transactional feature for application in memory Implements Multi Value Concurrency Control (MVCC) Atomic, Consistent, and Isolated
Lisp Ideology
LISP Lisp is worth learning for the profound enlightenment experience you will have when you finally get it; that experience will make you a better programmer for the rest of your days, even if you never actually use Lisp itself a lot. - Eric Raymond, How to Become a Hacker
Homoiconicity Code is data is code
Macro System Extends language syntax
Java Integration
Java Interop Plethora of libraries Highly performant Wide deployment Calling Java from Clojure and vice versa
What you get from Clojure Power: JVM/CLR/JS Robustness: functional Concurrency: STM Focus: lisp
Suggestion Focus on the core. Ignore the edges.
Suggestion Go slow
Getting Started Download clojure zip from clojure.org/downloads Run: java –cp clojure.jar clojure.main
REPL Interactive environment for faster development Read-Eval-Print-Loop ns expression user => (+ 3 4) 7 result user =>
Let’s code a bit
Namespace Define modules Avoid collision Format: (ns name & references) Example: (ns svcc)
Symbols Symbols are used to name functions, values, etc. Example: str or concat
Keywords A keyword is like a Symbol except that it begins with a colon (:). It resolves to itself. Example: :foo => :foo
S-expressions Stands for "symbolic expression" List-based data structures that represent semi- structured data. Example: (def port 8080)
Form Any s-expression that evaluates to a value Example: (+ 2 3 4)
Atomic Data Types Clojure Example Java string “hello” String character a Character integer 10 Int/Long/BigInteger double 3.14159 Double double 3.14159M BigDecimal boolean true Boolean nil nil null symbol foo, + N/A keyword :foo, ::foo N/A
Data Structures Type Example Characteristics list (2 4 6 8) • singly linked • grows at front vector [2 4 6 8] • indexed • grows at end map {:fname “Rich”, :lname • key/value pairs “Hickey”} • unique key set #{2 4 6 8} • unordered • unique keys
Sequences An abstraction over traditional lisp lists Provides a view into the lists Are lazy Some functions on sequences: (first seq): returns first element (cons elem seq): prepends element
Syntax – (Prefix) Polish Notation The operator appears before the operands Format: (operator operand operand)
Structure list symbol string (println “Hello World”)
Semantics fn call argument (println “Hello World”)
Function Definition define fn fn name (defn add-numbers “Add two numbers” documentation [x y] arguments (println “result: ” (+ x y))) fn body
Comments Comments start with a semi-colon (do ;; line comment ;;; block comment (println “Hello World”) (println “GoodBye!”) ) ; end of line comment
Predicate It is a function that returns a boolean. The name ends with a ?. Example: even?
Higher Order Function Functions that have functions are parameters. Example: map, reduce
Essence vs Ceremony public class AddNumbers { public static void main(String args[]) { long sum = 0; for (int i = 1; i < 1001; i++) { sum += i; } System.out.println("The sum is: " + sum); } }
Essence vs Ceremony (println (reduce + (range 1 1001)))
Useful Functions count: returns number of items in a collection – (count *4 “hello” c+) => 3 apply: applies a function on the arguments – (apply – [10 5 2]) => 3
Program Flow if, if-not – (if test consequent alternative) cond, condp – (cond & clauses) when, when-not – (when test & body)
REPL: Doc Documentation can be viewed with the doc macro user=> (doc +) ------------------------- clojure.core/+ ([] [x] [x y] [x y & more]) Returns the sum of nums. (+) returns 0. nil
REPL: javadoc Opens a browser with the javadoc for the requested class user=> (javadoc java.util.Random) "http://java.sun.com/javase/6/docs/api/java/uti l/Random.html"
REPL: source Displays the source for the function user=> (source even?) (defn even? "Returns true if n is even, throws an exception if n is not an integer" {:added "1.0"} [n] (zero? (bit-and n 1))) nil
REPL: inspector Creates a Swing inspector on supplied object user=> (use 'clojure.inspector) nil user=> (inspect (Math/PI))
Java Class Import Importing java classes Format: (import & import-symbols-or-lists) Example: (import '(java.util Random) '(java.util Date))
Instantiate Java Class Format: (def instanceName (new ClassName)) Example: (def sdf (new SimpleDateFormat “yyyy-mm”)) Another way: (def sdf (SimpleDateFormat. “yyyy-mm”))
Java Member Access Format: (.method instance arguments) Example: (.parse sdf date-string)
Java Static Access Format: (Classname/staticMethod args*) Example: (Math/PI)
Calling Java from Clojure (import '(java.util Random)) (def rnd (Random.)) (.nextInt rnd 10)
Calling Clojure from Java public class ClojureGreeter { public static void main(String[] args) { RT.loadResourceScript("clojure_script.clj"); Var greet = RT.var("clj.sample", “say"); String result = (String) greet.invoke(“John"); System.out.println(“Greeting: " + result); } }
Error Handling All exceptions thrown are Runtime Exceptions. (try expr* catch-clause* finally-clause?) Example: (try (/ 1 0) (catch Exception e (println "in catch")) (finally (println "in finally")))
MultiMethods Provides a general indirect dispatching mechanism Dispatches based on type values, attributes, and metadata defmulti creates new multimethods defmethod create methods for defmulti
Compilation Flow
Abstract Syntax Tree
Clojure Compilation Flow
Clojure Compilation Macro
Macro System Allows extending the compiler Lot of clojure features are based on macros Transform code
Macro Example (defmacro def-print-fn [fn-name args & body] `(defn ~fn-name ~args (println "Invoking ...") ~@body)) (def-print-fn simple-call[] (println "This is a simple call function."))
Concurrency Mutation done in transaction Readers do not block writers Writers do not block readers First one to commit succeeds
Concurrency Mechanism Shared data Synchronous Coordinated Change Ref Yes Yes Yes Atom Yes Yes No Agent Yes No No Var No No No
Leinengin Build tool Commands – compile, test, jar, install, pom, repl
IDE Support Eclipse Counterclockwise IntelliJ IDEA La Clojure Netbeans Enclojure JEdit Emacs Vim Clooj
Clojure and the Web Compojure Ring Noir Heroku support
Resources http://www.clojure.org http://dev.clojure.org http://clojuredocs.org http://planet.clojure.in http://clojure-libraries.appspot.com http://try-clojure.org http://nealford.com
Cheat Sheet http://clojure.org/cheatsheet
… and one last thing
Steve, you’re simply Great!
Thank You!

Introduction to clojure