Clojure made really really simple

Download Clojure made really really simple

Post on 16-Apr-2017

1.228 views

Category:

Technology

2 download

Embed Size (px)

TRANSCRIPT

<p>made really reallysimple</p> <p>Talk</p> <p>Why Clojure ?</p> <p>Why get functional ?</p> <p>4 cores in a Mac book Pro for developers</p> <p>Clock speeds peeks at ~3GHz in 2005</p> <p>Moores law - now about CPU coresLaptops with 128 cores by 2020 ??</p> <p>Parallelism over Concurrency at the hardware levelNot just multi-threading and hyper-threading</p> <p>What is Clojure</p> <p>Clojure is small and flexible</p> <p>Clojure concepts</p> <p>Encourages Pure Functional approach - use STM to change state </p> <p>Functions as first class citizens - functions as arguments as they return a value</p> <p>Make JVM interoperation simple- easy to use your existing Java applications</p> <p>Hickey's primary interest was concurrency he wanted the ability to write multi-threaded applications, but increasingly found the mutable, stateful paradigm of object oriented programming to be part of the problem</p> <p>The idea of a functional Lisp integrated with a commercially accepted host platform just seemed like chocolate and peanut butter. Coming up with persistent data structures that were fast enough was the tipping point for my considering it viable.</p> <p>functions as first-class objects, meaning that functions can be placed into data structures, passed as arguments to other functions, evaluated in comparisons, even returned as the return value of another function. Moreover, functions do not have "side effects" the ability to modify program state or data. This paradigm focuses on computation in the mathematical sense, rather than procedural algorithms, and is a completely different approach to programming.</p> <p>Clojure does provide persistent data structures For application developers, the most significant distinction is that Clojure defaults to making all data structures immutable</p> <p>developers must use one of four special mutable structures that are explicitly designed to be shared between threads: refs, vars, atoms, and agents. Clojure uses software transactional memory (STM) to coordinate changing these mutable structures while keeping them in a consistent state, much like a transactional database. This model makes it considerably simpler to write thread-safe code than it is in object oriented languages. No locks are required, therefore there are no deadlocks or race conditions.</p> <p>A better Lisp !</p> <p>Sensible () usage</p> <p>Sensible macro names</p> <p>JVM Interoperability </p> <p>Clojure has a programmatic macro system which allows the compiler to be extended by user code</p> <p>You can add your own language features with macros. Clojure itself is built out of macros such as defstruct:</p> <p> (defstruct person :first-name :last-name)</p> <p>If you need different semantics, write your own macro. If you want a variant of structs with strong typing and configurable null-checking for all fields, you can create your own defrecord macro, to be used like this:</p> <p> (defrecord person [String :first-name String :last-name] :allow-nulls false)This ability to reprogram the language from within the language is the unique advantage of Lisp. You will see facets of this idea described in various ways: Lisp is homoiconic - Lisp code is just Lisp data. This makes it easy for programs to write other programs.The whole language is there, all the time. Paul Grahams essay Revenge of the Nerds explains why this is so powerful. http://www.paulgraham.com/icad.html</p> <p>Lisp syntax also eliminates rules for operator precedence and associativity, with fully parenthesized expressions, there is no possible ambiguity</p> <p>Which LISP is your wingman ?</p> <p>Common Lisp</p> <p>Clojure</p> <p>The dark side of Clojure</p> <p> ( x )</p> <p>The downside of Lisps simple, regular syntax, at least for beginners, is Lisps fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.</p> <p>The dark side of Clojure</p> <p> ( ( x ) )</p> <p>The downside of Lisps simple, regular syntax, at least for beginners, is Lisps fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.</p> <p>The dark side of Clojure</p> <p> ( ( ( x ) ) )</p> <p>The downside of Lisps simple, regular syntax, at least for beginners, is Lisps fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.</p> <p>The dark side of Clojure</p> <p> ( ( ( ( x ) ) ) )</p> <p>The downside of Lisps simple, regular syntax, at least for beginners, is Lisps fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.</p> <p>The dark side of Clojure</p> <p> ( ( ( ( ( x ) ) ) ) )</p> <p>The downside of Lisps simple, regular syntax, at least for beginners, is Lisps fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.</p> <p>() == { () };</p> <p>...verses non-lisp languages</p> <p>([] ((()))) =={ ({([])}) };</p> <p>Well nearly....</p> <p>Comparing JavawithClojure</p> <p>Its all byte code in the end..</p> <p>Any object in clojure is just a regular java object</p> <p>A reference type inheriting from:java.lang.object</p> <p>Prefix notation</p> <p>(defn square-the-number [x] (* x x))</p> <p>Immutable Data structures</p> <p>List Ordered collection</p> <p>(list 1 3 5 7)</p> <p>'(1 3 5 7)</p> <p>(1 2 3) ; 1 is not a function</p> <p>Vectors hashed ordered list</p> <p>[:matrix-characters [:neo :morpheus :trinity :smith]]</p> <p>(first [:neo :morpheus :trinity :smith])</p> <p>(nth [:matrix :babylon5 :firefly :stargate] 2)</p> <p>(concat [:neo] [:trinity]) </p> <p>Maps unordered key/values</p> <p>{:a 1 :b 2} {:a 1, :b 2}</p> <p>{ :a 1 :b }java.lang.ArrayIndexOutOfBoundsException: 3</p> <p>{ :a 1 :b 2} {:a 1, :b 2}</p> <p>{:a {:a 1}} {:a {:a 1}}</p> <p>{{:a 1} :a} {{:a 1} :a}; idiom - put :a on the left</p> <p>Lists are for code</p> <p>Vectors are for data</p> <p>Defining a data structure</p> <p>( def my-data-structure [ data ] )</p> <p>( def days-of-the-week [Monday Tuesday Wednesday])</p> <p>Example data structure</p> <p>(def jr0cket {:first-name "John", :last-name "Stevenson"})</p> <p>Get coding !</p> <p>clojure.orgdocs.clojure.org</p> <p>All hail the REPL</p> <p>An interactive shell for clojure</p> <p>Fast feedback loop for clojure</p> <p>Managing a clojure project</p> <p>Maven</p> <p>Just like any other Java project</p> <p>Step 1)Add Clojure library jar to your POM</p> <p>Step 2)Download the Internet !!!</p> <p>Leiningen</p> <p>lein newlein depslein repllein swank</p> <p>Create a new clojure project</p> <p>Download all dependencies</p> <p>Start the interactive shell (repl)</p> <p>Start repl server</p> <p>leiningen.org</p> <p>Emacs</p> <p>A few interesting Clojure examples</p> <p>Ratio </p> <p>Unique data type</p> <p>Allow lazy evaluation</p> <p>Avoid loss of precision</p> <p>(/ 2 4)(/ 2.0 4)</p> <p>(/ 1 3)(/ 1.0 3)</p> <p>(class (/ 1 3)</p> <p>Calling Java... ooooo!!</p> <p>(javax.swing.JOptionPane/ showMessageDialog nil "Hello World" )</p> <p>Importing Java into Clojure </p> <p>(ns drawing-demo (:import [javax.swing Jpanel JFrame] [java.awt Dimension]))</p> <p>Working with Java</p> <p>Java Classes fullstop after class name(JFrame. )(Math/cos 3) ; static method call</p> <p> Java methodsfullstop before method name(.getContentPane frame) ;;method name first(. frame getContentPane) ;;object first</p> <p>What class is that...</p> <p>(class (str "Jr0cket"))java.lang.String</p> <p>(class (defn hello-world [name] (str "Hello cruel world")))clojure.lang.Var</p> <p>Clojure calling Java web stuff</p> <p>(let [conn] (doto (HttpUrlConnection. Url) (.setRequestMethod POST) (.setDoOutput true) (.setInstaneFollowRedirects true))])</p> <p>Recursive functions</p> <p>Functions that call themselves</p> <p>Fractal coding</p> <p>Tail recursion</p> <p>Avoids blowing the stack</p> <p>A trick as the JVM does not support tail recursion directly :-(</p> <p>Tail recursion</p> <p>(defn recursive-counter (print answer) (if (&lt; answer 1000) (recur (+ answer 4))))</p> <p>This is barfing because the evaluator has to keep around state for each call due to the expression (* x (factorial (- x 1))) . We need to make this function tail recursive.</p> <p>recur can be thought of as the Clojure operator for looping. Think of it like a function call for the nearest enclosing let or function definition supplied with new variables. Naively we can switch over to using this by doing:</p> <p>user&gt; (defn factorial2 [x] (if (= x 0) 1 (* x (recur (- x 1)))))</p> <p>But this is a compile-time error (which in itself is pretty neat!).java.lang.UnsupportedOperationException: Can only recur from tail position (NO_SOURCE_FILE:4)</p> <p>An accumulator parameter is an extra parameter to a function that's used to gather intermediate parts of the calculation. If we do this, we can make sure that the recur call is in the tail position. Using an anonymous function we get:</p> <p>(defn factorial3 [x] ((fn [x y] (if (= x 0) y (recur (- x 1) (* x y)))) x 1))</p> <p>Now when recur is used, it doesn't need to keep any of the previous stack frame around. This means we can finally calculate factorial 1000000, which begins with 282 and ends with lots of zeros! </p> <p>Where to find out more...</p> <p>clojure.org/cheatsheet</p> <p>Mutable State</p> <p>Software Transactional Memory</p> <p>Provides safe, concurrent access to memory</p> <p>Agents allow encapsulated access to mutable resources</p> <p>Functional Web</p> <p>Noir webnoir.org</p> <p>Hiccuplibrary for representing HTML in Clojure. It uses vectors to represent tags, and maps to represent a tag's attributes.</p> <p>Thank you</p> <p>London Clojurians</p> <p>clojure.org@jr0cketclojure.jr0cket.co.uk</p> <p>Muokkaa otsikon tekstimuotoa napsauttamalla</p> <p>Muokkaa jsennyksen tekstimuotoa napsauttamallaToinen jsennystasoKolmas jsennystasoNeljs jsennystasoViides jsennystasoKuudes jsennystasoSeitsems jsennystasoKahdeksas jsennystasoYhdekss jsennystaso</p>