Seeking Clojure


Published on

Brown bag presentation on Clojure, given on March 8th 2012.

Accompanying code available at:

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Seeking Clojure

  1. 1. Seeking Clojure Chris Rice, 8th March 2012
  2. 2. Clojure• First appeared in 2007• Created by Rich Hickey• Currently at version 1.3• Released under Eclipse Public License• Available at
  3. 3. Clojure is......Functional...Dynamic...Dynamically Typed...a JVM Language (or a CLR language!)...a Lisp
  4. 4. Clojure as a Functional LanguageClojure is a functional programming language. It provides the tools toavoid mutable state, provides functions as first-class objects, andemphasises recursive iteration instead of side-effect based looping.Clojure is impure, in that it doesnt force your program to bereferentially transparent, and doesnt strive for provable programs.The philosophy behind Clojure is that most parts of most programsshould be functional, and that programs that are more functional aremore robust. -
  5. 5. Clojure as a Dynamic LanguageClojure is a dynamic language. Source code is not just something that is compiledand run, but something with which a developer can fully interact.Within the Clojure environment, almost all language constructs can be examinedand modified at runtime.This leads to a substantially different experience from running a program, examiningits results and trying again. In particular, you can grow your program, with dataloaded, adding features, fixing bugs, testing, in an unbroken stream.The REPLThe primary programming interface for Clojure development is the Read-Eval-Print-Loop (REPL). This is a console interface that allows you to enter and executecommands, and examine their results immediately.
  6. 6. Clojure as a Dynamically Typed languageUnlike Java, Clojure is a dynamically typed language.A programming language is said to be dynamically typed when the majority of itstype checking is performed at run-time as opposed to at compile-time. In dynamictyping values have types, but variables do not; that is, a variable can refer to a valueof any type.Clojure supports a concept called Type Hinting, which assists the compiler inavoiding reflection in performance-critical areas of code.
  7. 7. Clojure as a JVM LanguageClojure compiles to byte-code which executes on the Java Virtual Machine.(Additionally, there is an ongoing project to port Clojure to the .NET CommonLanguage Runtime.)Unlike many JVM languages, where interoperability is assumed as a side-effect of theruntime environment, Clojure has made solid integration with the Java language acore design goal.Clojure programs can use all Java classes and interfaces. As with Java, classes in thejava.lang package can be used directly without importing them.Mechanism has also been provided to allow Clojure code to be executed fromwithin Java programs.
  8. 8. Clojure as a LispLisp (originally an acronym for LISt Processing) is a family of languages, the first ofwhich appeared in 1958.As a Lisp, the syntax and constructs used within Clojure are well-established. Clojure builds upon Lisp by addinga number of convenient additions and a little bit of syntactic sugar!Lisp syntax is rather different from Java/C++ syntax. It can take a little bit of getting used to, but is actuallyextremely consistent and can lead to very concise and expressive code.
  9. 9. Syntax
  10. 10. Data TypesData Type ExampleNumbers 1 3.14 22/7Characters a b cStrings "this is a string"Regular Expressions #”[0-9]+”Symbols a b cKeywords :a :b :cLists (1 2 3)Vectors [1 2 3]Maps {:a 1 :b 2 :c 3}Sets #{1 2 3}
  11. 11. HomoiconicityHomoiconicity is a property of some programming languages, in which the primaryrepresentation of programs is also a data structure in a primitive type of thelanguage itself.Clojure, as a member of the Lisp family, is a homoiconic language. Expressions arewritten as lists, using Polish prefix notation:(map (fn [x] (* x 2)) (list 1 2 3))In Clojure, code IS data. As a result, code can be generated and manipulated atruntime in the same way as any other data structure (metaprogramming!). As witha number of other Lisp dialects, this is achieved through the use of macros.
  12. 12. S-ExpressionsThe list-based expressions described on the previousslide are known in Clojure, and other dialects of Lisp, asS-Expressions. (symbol parameter1 parameter2 ... parameterN)Parameters can be any data type, including functions -as seen in the previous example: (map (fn [x] (* x 2)) (list 1 2 3))In terms of syntax, that’s pretty much it! * * well, almost
  13. 13. BindingsClojure doesnt truly support variables. Instead it provides bindings which are fairlysimilar to final variables - in that they are not intended to be changed after initialvalue is assigned. *Bindings link values to symbols. There are global bindings, thread-local bindings,bindings that are local to a function, and bindings that are local to a given form.To bind a value to a symbol, the following syntax is used:(def language "Clojure")In the example above, after binding, evaluating the symbol language will returnthe string "Clojure". * can be misused
  14. 14. FunctionsFunctions can be created anonymously in the following way:(fn [x y] (* x y)) ; a pointless functionIn order to allow re-use, a function can be bound to a symbol just like any otherdata type:(def multiply (fn [x y] (* x y))) ; still pointlessAs this is a fairly common practice, Clojure provides a shorthand for binding afunction to a symbol:(defn multiply [x y] (* x y)) ; just as pointless
  15. 15. Hello World
  16. 16. MacrosClojure, like many other variants of Lisp, has a programmatic macro system whichallows the compiler to be extended by user code.Macros can be used to define syntactic constructs which would require primitivesor built-in support in other languages. Many core constructs of Clojure are notprimitives, but are in fact normal macros.While functions always evaluate all of their arguments, macros allow deferral ofevaluation and can decide which will in fact be evaluated. This is because a macrooperates (or expands) prior to compile time of a Clojure program.Consider the following higher-order function:(defn do-something-twice [f] (do f f))
  17. 17. MultimethodsJava methods can be overloaded based on both arity and parameter type. Clojurefunctions can only be overloaded on arity.(defn overload-on-arity ([] "None") ([_] "One") ([_ & _] "More Than One"))Multimethods provide a mechanism to overload a function based on anything, bydispatching to specific implementations as a result of the evaluation of a providedfunction.(defmulti name dispatch-function)(defmethod name dispatch-result [params] result)
  18. 18. SequencesSequences are logical views of collections. Many things can be treated as sequences.These include Java collections, Clojure-specific collections, strings, streams,directory structures and XML trees.Many Clojure functions return a lazy sequence. This is sequence whose items can bethe result of function calls that arent evaluated until they are needed.A benefit of creating a lazy sequence is that it isnt necessary to anticipate howmany items in it will actually be used at the time the sequence is created.
  19. 19. Java InteroperabilityAs mentioned previously, Java interoperability was a core design goal of Clojure,rather than a side effect of living in the JVM.Running Clojure code from Java:// Java calling codeRT.loadResourceScript("core.clj");RT.var("hcom.core", "hello").invoke("World");Instantiating Java objects and invoking methods from Clojure:(import java.util.Date)(.getTime (new Date))Also important to note that native Clojure data structures implement Javainterfaces. Clojure Vectors implement java.util.Collection. Clojure Mapsimplement java.util.Map. Clojure functions implement java.lang.Runnable.
  20. 20. ConcurrencyTodays systems have to deal with multiple simultaneous tasks.Doing so with threads can be problematic due to the complexitiesof synchronisation.Clojure simplifies multi-threaded programming by default - becausethe core data structures are immutable, they can be shared readilybetween threads.Obviously, it is often necessary for state to change within aprogram. Clojure, being a practical and pragmatic language, allowsstate to change but provides mechanisms to ensure that, when itdoes so, it remains consistent, while alleviating developers fromhaving to avoid conflicts manually using locks.
  21. 21. ConcurrencyClojure provides four different mechanisms for addressing state change:VarsVars offers the ability to alter the binding of a value to a symbol in a context local to a single thread. This bindingwill not be apparent to other threads, and where a binding is not explicitly defined the root binding will remain.AtomsAtoms provide a single logically atomic mechanism for reading, modifying and writing a shared value in anindependent and synchronous matter.AgentsClojure Agents are similar to the concept of local Actors, but with an inversion of message-handling logic. Ratherthan state being sent to the ‘mailbox’ of an Actor which houses a piece of functionality, state lives within a ClojureAgent and functions to be applied to that state are sent to the Agent’s ‘mailbox’.RefsRefs ensure safe shared use of mutable storage locations via a software transactional memory (STM) system. Refsare bound to a single storage location for their lifetime, and only allow mutation of that location to occur within atransaction. Similarly to database transactions, either all mutations within a transaction occur or none do.
  22. 22. Libraries and FrameworksThere are a number of Clojure frameworks and libraries which provide a whole range of additional extensionsand enhancements to the Clojure language. A few of the more popular and interesting are:clojure-contrib - collection of user-submitted extensions to the Clojure language.Noir - lightweight web framework, with an emphasis on simplicity and speed of development.Incanter - platform for statistical computation and charting/graphics.Overtone - musical exploration platform designed to facilitate synthesis and sampling, instrument building, live-coding andcollaborative jamming.
  23. 23. TestingThe main Clojure distribution includes a simple testingframework called clojure.test.(deftest test-fizzbuzz (is (= "FizzBuzz" (fizzbuzz 15))))Tests can be executed at the REPL using the (run-test)function:Ran 4 tests containing 20 assertions.0 failures, 0 errors.{:type :summary, :pass 20, :test 4, :error 0, :fail 0}
  24. 24. ToolsWhile the Clojure tooling ecosystem remains relatively anaemic, there are a couple of tools which have becomede facto standards within the Clojure community.Leiningen - is a build tool and dependency manager for Clojure which includes the ability to set up an interactiveREPL with the appropriately configured classpath. There are a number of plugins available for Leiningen, such a Noirplugin that enables simple creation of an empty web project as well as a target for running the project within a Jettycontainer.EmacsWhile Emacs is hardly a Clojure-specific tool, it is by far the most popular environment within the Clojurecommunity for development. Much of Emacs is written in Lisp, and its configuration files are themselvesconstructed using a Lisp dialect. There are a number of plugins to simplify Lisp and Clojure development, such asparedit, clojure-mode and slime.IDE PluginsIf using Emacs doesn’t appeal, there are Clojure plugins available for Eclipse (Counterclockwise), IntelliJ (La Clojure)and Netbeans (enclojure). A Clojure TextMate bundle is available, as well as a vim plugin (vimclojure).
  25. 25. clojure/core.futureClojure is still evolving. Contributed libraries arecontinually being pulled into the core distribution.clojure/core.logicLogic programming extension for Clojure.clojure/core.matchPattern matching extension for Clojure. Similar to pattern matching seen in Scalaand Haskell.
  26. 26. FizzBuzz in a Tweet *(defn fizzbuzz [n] (match [(mod n 3) (mod n 5)] [0 0] "FizzBuzz" [0 _] "Fizz" [_ 0] "Buzz" :else n)) * not my code!
  27. 27. Useful Referenceshttp://www.clojuredocs.org (not free)
  28. 28. Groups + ConferencesLondon Clojure Group 2012 London, May 24th-25th eXchange 2012 London, December 6th
  29. 29. Questions?