Introduction to clojure

2,430 views
2,352 views

Published on

An introduction to clojure presented at Silicon Valley Code Camp 2011.

Published in: Technology, Education
0 Comments
11 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,430
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
11
Embeds 0
No embeds

No notes for slide

Introduction to clojure

  1. 1. Introduction to Clojure Programming Silicon Valley Code Camp October 8th, 2011 Abbas Raza
  2. 2. Myselfuser => (def speaker { :name “Abbas Raza” :company “SuccessFactors” :team “Platform Engineering” :twitter “theceo”})
  3. 3. Clojure FoundationGetting StartedBuilding Blocks
  4. 4. Advanced TopicsComparing LanguagesComparing Paradigms
  5. 5. Thanks!Rich Hickey Clojure Creator
  6. 6. What is ClojureGeneral Purpose LanguageDynamicFunctionalLisp StrengthsJava/CLR/Javascript
  7. 7. Clojure - TimelineFirst released October 16, 20071.0 released 05/04/091.1 released 12/31/091.2 released 08/19/101.3 released 09/23/11ClojureScript released July, 2011
  8. 8. Who’s using Clojure?http://dev.clojure.org/display/community/Clojure+Success+Stories
  9. 9. Functional Programming
  10. 10. H/W Perf Free Lunch is overhttp://www.gotw.ca/publications/concurrency-ddj.htm
  11. 11. Functional ProgrammingNo side effects – immutableFunctions are first class citizensFunctions passed in as parametersFunctions return functionsFunctions can be created at runtime
  12. 12. Software Transactional MemoryProvides transactional feature for application in memoryImplements Multi Value Concurrency Control (MVCC)Atomic, Consistent, and Isolated
  13. 13. Lisp Ideology
  14. 14. 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
  15. 15. HomoiconicityCode is data is code
  16. 16. Macro SystemExtends language syntax
  17. 17. Java Integration
  18. 18. Java InteropPlethora of librariesHighly performantWide deploymentCalling Java from Clojure and vice versa
  19. 19. What you get from ClojurePower: JVM/CLR/JSRobustness: functionalConcurrency: STMFocus: lisp
  20. 20. SuggestionFocus on the core.Ignore the edges.
  21. 21. SuggestionGo slow
  22. 22. Getting StartedDownload clojure zip from clojure.org/downloadsRun:java –cp clojure.jar clojure.main
  23. 23. REPLInteractive environment for faster developmentRead-Eval-Print-Loopns expressionuser => (+ 3 4)7 resultuser =>
  24. 24. Let’s code a bit
  25. 25. NamespaceDefine modulesAvoid collisionFormat:(ns name & references)Example:(ns svcc)
  26. 26. SymbolsSymbols are used to name functions, values, etc.Example:str or concat
  27. 27. KeywordsA keyword is like a Symbol except that it begins with a colon (:).It resolves to itself.Example::foo => :foo
  28. 28. S-expressionsStands for "symbolic expression"List-based data structures that represent semi- structured data.Example:(def port 8080)
  29. 29. FormAny s-expression that evaluates to a valueExample:(+ 2 3 4)
  30. 30. Atomic Data TypesClojure Example Javastring “hello” Stringcharacter a Characterinteger 10 Int/Long/BigIntegerdouble 3.14159 Doubledouble 3.14159M BigDecimalboolean true Booleannil nil nullsymbol foo, + N/Akeyword :foo, ::foo N/A
  31. 31. Data StructuresType Example Characteristicslist (2 4 6 8) • singly linked • grows at frontvector [2 4 6 8] • indexed • grows at endmap {:fname “Rich”, :lname • key/value pairs “Hickey”} • unique keyset #{2 4 6 8} • unordered • unique keys
  32. 32. SequencesAn abstraction over traditional lisp listsProvides a view into the listsAre lazySome functions on sequences: (first seq): returns first element (cons elem seq): prepends element
  33. 33. Syntax – (Prefix) Polish NotationThe operator appears before the operandsFormat:(operator operand operand)
  34. 34. Structurelist symbol string(println “Hello World”)
  35. 35. Semantics fn call argument(println “Hello World”)
  36. 36. Function Definitiondefine fn fn name(defn add-numbers “Add two numbers” documentation [x y] arguments (println “result: ” (+ x y))) fn body
  37. 37. CommentsComments start with a semi-colon(do ;; line comment ;;; block comment (println “Hello World”) (println “GoodBye!”) ) ; end of line comment
  38. 38. PredicateIt is a function that returns a boolean.The name ends with a ?.Example:even?
  39. 39. Higher Order FunctionFunctions that have functions are parameters.Example:map, reduce
  40. 40. Essence vs Ceremonypublic 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); }}
  41. 41. Essence vs Ceremony(println (reduce + (range 1 1001)))
  42. 42. Useful Functionscount: returns number of items in a collection – (count *4 “hello” c+) => 3apply: applies a function on the arguments – (apply – [10 5 2]) => 3
  43. 43. Program Flowif, if-not – (if test consequent alternative)cond, condp – (cond & clauses)when, when-not – (when test & body)
  44. 44. REPL: DocDocumentation can be viewed with the docmacrouser=> (doc +)-------------------------clojure.core/+([] [x] [x y] [x y & more]) Returns the sum of nums. (+) returns 0.nil
  45. 45. REPL: javadocOpens a browser with the javadoc for therequested classuser=> (javadoc java.util.Random)"http://java.sun.com/javase/6/docs/api/java/uti l/Random.html"
  46. 46. REPL: sourceDisplays the source for the functionuser=> (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
  47. 47. REPL: inspectorCreates a Swing inspector on supplied objectuser=> (use clojure.inspector)niluser=> (inspect (Math/PI))
  48. 48. Java Class ImportImporting java classesFormat: (import & import-symbols-or-lists)Example:(import (java.util Random) (java.util Date))
  49. 49. Instantiate Java ClassFormat: (def instanceName (new ClassName))Example:(def sdf (new SimpleDateFormat “yyyy-mm”))Another way:(def sdf (SimpleDateFormat. “yyyy-mm”))
  50. 50. Java Member AccessFormat: (.method instance arguments)Example:(.parse sdf date-string)
  51. 51. Java Static AccessFormat: (Classname/staticMethod args*)Example:(Math/PI)
  52. 52. Calling Java from Clojure(import (java.util Random))(def rnd (Random.))(.nextInt rnd 10)
  53. 53. Calling Clojure from Javapublic 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); }}
  54. 54. Error HandlingAll 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")))
  55. 55. MultiMethodsProvides a general indirect dispatching mechanismDispatches based on type values, attributes, and metadatadefmulti creates new multimethodsdefmethod create methods for defmulti
  56. 56. Compilation Flow
  57. 57. Abstract Syntax Tree
  58. 58. Clojure Compilation Flow
  59. 59. Clojure Compilation Macro
  60. 60. Macro SystemAllows extending the compilerLot of clojure features are based on macrosTransform code
  61. 61. 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."))
  62. 62. ConcurrencyMutation done in transactionReaders do not block writersWriters do not block readersFirst one to commit succeeds
  63. 63. ConcurrencyMechanism Shared data Synchronous Coordinated ChangeRef Yes Yes YesAtom Yes Yes NoAgent Yes No NoVar No No No
  64. 64. LeinenginBuild toolCommands – compile, test, jar, install, pom, repl
  65. 65. IDE SupportEclipse CounterclockwiseIntelliJ IDEA La ClojureNetbeans EnclojureJEditEmacsVimClooj
  66. 66. Clojure and the WebCompojureRingNoirHeroku support
  67. 67. Resourceshttp://www.clojure.orghttp://dev.clojure.orghttp://clojuredocs.orghttp://planet.clojure.inhttp://clojure-libraries.appspot.comhttp://try-clojure.orghttp://nealford.com
  68. 68. Cheat Sheethttp://clojure.org/cheatsheet
  69. 69. … and one last thing
  70. 70. Steve,you’resimplyGreat!
  71. 71. Thank You!

×