Clojureand Swing – a new productivity sweet spot?<br />Simon White<br />
Skills Matter<br />The UK Open Source Training Company<br />Training on: Agile Development, Test Driven Development, Java,...
Speaker Qualifications<br />Simon White, IndependentJava developer<br />Games published 1985<br />PhD Artificial Intellige...
What is Clojure?<br />A functional language that runs on the JVM<br />A new dialect of LISP<br />Not Closure<br />Not Cloz...
Functional Languages<br />What is a function?<br />a mathematical relation such that each element of a given set (the doma...
LISP Syntax<br />(functor param1 param2 ... paramn)<br />for example, (+ 1 2)<br />Brackets denote evaluation<br />A singl...
Hello Factorial<br />n! = n × (n-1) × (n-2) × ... × 1<br />Also 0! = 1<br />(defnfac<br /> “Computes the factorial of n”<b...
REPLRead-Evaluate-Print-Loop<br />user=> (defn add-one [n] (+ 1 n))<br />#'user/add-one<br />user=> (add-one 6)<br />7<br ...
Java vs. LISP<br />
Why mix Java and LISP?<br />To get the best of both:<br />Speedy development of custom code in LISP<br />Speedy developmen...
LISP Promotes Agility<br />LISP was agile long before agility was respected <br />Easy to mix and match function applicati...
Clojureas a LISP dialect<br />Simplified syntax compared to Common LISP<br />cond, let<br />Not object-oriented<br />But y...
Data Structures 1: Lists<br />(list 'a 'b 'c) -> (a b c)<br />(first '(a b c)) -> a<br />(rest '(a b c)) -> (b c)<br />(nt...
Data Structures 2: Vectors<br />(vector 'a 'b 'c) -> [a b c]<br />(first '[a b c]) -> a<br />(rest '[a b c]) -> (b c)<br /...
Data Structures 3: Maps<br />Key-Value Pairs<br />(get '{a 1, b 2} 'b) -> 2<br />(assoc '{a 1, b 2} 'c 3) -> {c 3, a 1, b ...
Everything is a Sequence<br />Lists, Vectors and Maps are all sequences<br />first, rest & cons always return a sequence<b...
Predicates (Boolean-Valued Tests)<br />(= a 10)<br />(identical? a b)<br />(even? a)<br />(odd? a)<br />(integer? a)<br />
Decisions<br />(if (= a 1) 5 0)<br />(cond<br />     (= a 1) 5 <br />     (= a 2) 10<br />     true 0)<br />(when (= a 1) ...
"Iteration"<br />(for [a '(1 2 3)] (+ a 1)) -> (2 3 4)<br />(doseq [a (range 5)] a) -> nil<br />(doseq [a (range 3)] (prin...
Anonymous Functions<br />user=> (fn [a b] (+ a b 1))<br />#<user$eval__101$fn__103 ...@a613f8><br />user=> ((fn [a b] (+ a...
Higher Order Functions<br />(inc 1)->2<br />(map inc '(1 2 3))->(2 3 4)<br />(map + '(1 2 3) '(10 11 12))->(11 13 15)<br /...
Partial Functions<br />Partial returns a function<br />user=> (def add-two (partial + 2))<br />#'user/add-two<br />user=> ...
Java Interoperability<br />
A GUI in a functional language?<br />Functional languages use functions as mathematical models of computation:<br />f(x1, ...
Need to Think Differently<br />Values of functions ‘computed’ as the result of a user-interaction<br />Consider y-or-n-p<b...
Modelling Change of State<br />f(x) -> x’<br />Name: “George”<br />DOB: “11-Jul-73”<br />Address: “16 Goldman Square”<br /...
Java Swing: Create a JFrame<br />import javax.swing.JFrame;<br />public class MyClass {<br />...<br />  public static void...
Clojure Swing: Create a JFrame<br />(ns user<br />  (:import (javax.swingJFrame)))<br />(defn make-frame []<br />  (let [f...
Alternative: Use doto<br />(defn make-frame []<br />  (let [f (JFrame. "My Frame")]<br />   (doto f<br />      (.setBounds...
Create a Panel & Button<br />(ns user<br />  (:import java.awt.FlowLayout<br />    (javax.swingJButtonJPanel)))<br />(defn...
Make a Button do Something<br />(defn make-panel2 []<br />  (let [panel (JPanel. (FlowLayout.))<br />        button (JButt...
Clojure Custom Component<br />(defn make-component [msg]<br />  (proxy [javax.swing.JComponent] []<br />    (paintComponen...
Custom Component (cont/d)<br />(doto g<br />  (.setColorColor/gray)<br />  (.fillOval 20 20 (- width 20) (- height 20))<br...
Three ways in which Clojure can help Swing<br />Reducing boiler-plate code<br />Easy to write code that generates the requ...
1. Reducing Boiler-Plate Code<br />GridBagConstraints c = new GridBagConstraints();<br />c.weighty = 1.0;<br />c.weightx =...
Use the same options a lot of the time
Difficult to understand</li></li></ul><li>Using a grid-bag-layout macro<br />(def panel<br />     (doto (JPanel. (GridBagL...
2. Defining Swing Actions<br />Swing Actions are a nice idea, but have problems. <br />Typically, you might have:<br />Lot...
Clojure Actions: Defer binding for actionPerformed method<br />With an Action in Clojure it’s possible to preset the ‘cons...
Create an Action when the handler function is known<br />(defmacro copy-action [handler]<br /> `(make-action <br />  {:nam...
3. Flexibility and Reusability<br />(def *tracing-actions* true)<br /> <br />(defntrace-action [handler]<br />  (fn [#^Act...
Swing Worker & Busy Cursor<br />(defmacro with-busy-cursor<br />  [component f]<br />  `(proxy [SwingWorker] []<br />    (...
Clojure/Swing in the Real World<br />
Creating a Chart Model<br />(defn make-model<br />  "Create and return a ChartModel using the supplied rows and picking ou...
Upcoming SlideShare
Loading in …5
×

Clojure And Swing

7,905 views

Published on

Clojure is a new dialect of LISP that runs on the Java Virtual Machine (JVM). As a functional language, it offers great benefits in terms of programmer productivity; as a language that runs on the JVM, it also offers the opportunity to reuse existing Java libraries. Simon’s interest is in using Clojure to build desktop applications with the Java Swing GUI library. In this presentation Simon discusses how the power of Clojure can be applied to Swing, and whether it hits the sweet spot.

Published in: Technology, Art & Photos
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
7,905
On SlideShare
0
From Embeds
0
Number of Embeds
168
Actions
Shares
0
Downloads
96
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide
  • A closure is a feature provided by some languages that capture the lexical context in which a code fragment was written. The free variables in that lexical context are ‘closed over’ so the code fragment can be passed around and used elsewhere.Clozure is a dialect of LISP for the Mac (formerly Macintosh Common LISP)
  • defn defines a function
  • You can also create GUI elements such as JFrames and JButtons on the fly.
  • There are only few libraries in LISP compared to Java because it is a niche language.However, the fact that it is a niche language could make it your secret weapon.
  • For is actually a list comprehension
  • Reasons for using partial functions: Binding parameters at different times (when they become known) Clearer semantics
  • ns specifies the name space for the functions that followlet allows you to define some local variables
  • ns specifies the name space for the functions that followlet allows you to define some local variables
  • Or if you create a new GridBagConstraints object often, you might not remember what all the constructor arguments are
  • The example with-busy-cursor is intended as an illustration only
  • Clojure And Swing

    1. 1. Clojureand Swing – a new productivity sweet spot?<br />Simon White<br />
    2. 2. Skills Matter<br />The UK Open Source Training Company<br />Training on: Agile Development, Test Driven Development, Java, Eclipse, Spring, Hibernate, Ajax, Ruby on Rails, Struts Ti, Wicket, JavaServer Faces, Tapestry, Beehive, AOP, RIFE and more!<br />Training straight from the Source<br />Experts write and teach our courses: Adrian Colyer, Chad Fowler, Howard M. Lewis Ship Craig Larman, Dave Crane, Kevlin Henney, Rob Harrop, Kito Mann, Rod Johnson and many more<br />Partners with leading edge companies<br />BEA, IBM, Interface21, Sun, Tangosol, wso2<br />© Catalysoft Ltd, 2010<br />
    3. 3. Speaker Qualifications<br />Simon White, IndependentJava developer<br />Games published 1985<br />PhD Artificial Intelligence<br />Written Scientific Software for:<br />Remote Sensing<br />Drug Discovery<br />Medical & Genetics Research<br />Swing Developer since 2000<br />Author of JIDE Charts<br />SkillsMatter Author & Trainer<br />© Catalysoft Ltd, 2010<br />
    4. 4. What is Clojure?<br />A functional language that runs on the JVM<br />A new dialect of LISP<br />Not Closure<br />Not Clozure<br />MYTH: LISP is slow<br />MYTH: Therefore Clojure is slow<br />
    5. 5. Functional Languages<br />What is a function?<br />a mathematical relation such that each element of a given set (the domain of the function) is associated with an element of another set (the range of the function)) [Wordnet]<br />Focus on the input/output relation<br />e.g. length of a string maps a string to an integer<br />Immutability Good; Side-effects Bad<br />
    6. 6. LISP Syntax<br />(functor param1 param2 ... paramn)<br />for example, (+ 1 2)<br />Brackets denote evaluation<br />A single quote protects from evaluation<br />so '(x y z) does not use x as a function<br />With nested expressions, evaluate inner expression first: (+ (+ 2 3) (* 2 3)) is 11<br />Special forms like let, cond deviate from the syntax and must be learned<br />
    7. 7. Hello Factorial<br />n! = n × (n-1) × (n-2) × ... × 1<br />Also 0! = 1<br />(defnfac<br /> “Computes the factorial of n”<br /> [n]<br /> (if (= n 0) <br /> 1 <br /> (* n (fac (- n 1)))))<br />
    8. 8. REPLRead-Evaluate-Print-Loop<br />user=> (defn add-one [n] (+ 1 n))<br />#'user/add-one<br />user=> (add-one 6)<br />7<br />user=> <br />
    9. 9. Java vs. LISP<br />
    10. 10. Why mix Java and LISP?<br />To get the best of both:<br />Speedy development of custom code in LISP<br />Speedy development through library reuse in Java<br />Speedy development of applications with concurrent processing<br />
    11. 11. LISP Promotes Agility<br />LISP was agile long before agility was respected <br />Easy to mix and match function application<br />Accommodate changing requirements<br />Many small functions => very reusable code<br />REPL Encourages ad-hoc testing<br />Functional style makes it easy to write unit tests<br />
    12. 12. Clojureas a LISP dialect<br />Simplified syntax compared to Common LISP<br />cond, let<br />Not object-oriented<br />But you can define structures and multi-methods<br />No multiple value returns<br />Arguably syntactic sugar anyway<br />Lazy evaluation of sequences<br />Destructuring<br />Structural pattern matching on function parameters<br />Concurrency<br />
    13. 13. Data Structures 1: Lists<br />(list 'a 'b 'c) -> (a b c)<br />(first '(a b c)) -> a<br />(rest '(a b c)) -> (b c)<br />(nth '(a b c) 1) -> b<br />(cons 'a '(b c)) -> (a b c)<br />(concat '(a b) '(c d)) -> (a b c d)<br />
    14. 14. Data Structures 2: Vectors<br />(vector 'a 'b 'c) -> [a b c]<br />(first '[a b c]) -> a<br />(rest '[a b c]) -> (b c)<br />(nth '[a b c] 1) -> b<br />(cons 'a '[b c]) -> (a b c)<br />(conj '[a b] 'c) -> [a b c]<br />(concat '[a b] '[c d]) -> (a b c d)<br />
    15. 15. Data Structures 3: Maps<br />Key-Value Pairs<br />(get '{a 1, b 2} 'b) -> 2<br />(assoc '{a 1, b 2} 'c 3) -> {c 3, a 1, b 2}<br />(dissoc '{a 1, b 2} 'b) -> {a 1}<br />(defstruct book :title :author)<br />(struct-map book :title "Jungle Book" :author "Rudyard Kipling") <br />(bean obj)<br />
    16. 16. Everything is a Sequence<br />Lists, Vectors and Maps are all sequences<br />first, rest & cons always return a sequence<br />(range 5) -> (0 1 2 3 4)<br />(take 2 (range 5)) -> (0 1)<br />(take 3 (repeat 'x)) -> (x xx)<br />
    17. 17. Predicates (Boolean-Valued Tests)<br />(= a 10)<br />(identical? a b)<br />(even? a)<br />(odd? a)<br />(integer? a)<br />
    18. 18. Decisions<br />(if (= a 1) 5 0)<br />(cond<br /> (= a 1) 5 <br /> (= a 2) 10<br /> true 0)<br />(when (= a 1) 5)<br />a == 1 ? 5 : 0<br />Java<br />
    19. 19. "Iteration"<br />(for [a '(1 2 3)] (+ a 1)) -> (2 3 4)<br />(doseq [a (range 5)] a) -> nil<br />(doseq [a (range 3)] (println a)) -><br />0<br />1<br />2<br />nil<br />
    20. 20. Anonymous Functions<br />user=> (fn [a b] (+ a b 1))<br />#<user$eval__101$fn__103 ...@a613f8><br />user=> ((fn [a b] (+ a b 1)) 3 4)<br />8<br />user=> #(+ %1 %2)<br />#<user$eval__121$fn__123 ...@56f631><br />
    21. 21. Higher Order Functions<br />(inc 1)->2<br />(map inc '(1 2 3))->(2 3 4)<br />(map + '(1 2 3) '(10 11 12))->(11 13 15)<br />(max 1 2 3)->3<br />(apply max '(1 2 3))->3<br />(filter even? (range 10))->(0 2 4 6 8)<br />
    22. 22. Partial Functions<br />Partial returns a function<br />user=> (def add-two (partial + 2))<br />#'user/add-two<br />user=> (add-two 5)<br />7<br />
    23. 23. Java Interoperability<br />
    24. 24. A GUI in a functional language?<br />Functional languages use functions as mathematical models of computation:<br />f(x1, x2, ...) -> x’<br />Great for factorials, but how does it work with user-interfaces?<br />Forms?<br />Keyboard & Mouse?<br />Events?<br />
    25. 25. Need to Think Differently<br />Values of functions ‘computed’ as the result of a user-interaction<br />Consider y-or-n-p<br />CL> (y-or-n-p "Do you really want to quit?")<br />T<br />
    26. 26. Modelling Change of State<br />f(x) -> x’<br />Name: “George”<br />DOB: “11-Jul-73”<br />Address: “16 Goldman Square”<br />Name: “George”<br />DOB: “11-Jul-73”<br />Address: “3 Elm Avenue”<br />This is a new (immutable) value,<br />not a modified one<br />
    27. 27. Java Swing: Create a JFrame<br />import javax.swing.JFrame;<br />public class MyClass {<br />...<br /> public static void main(String[] args) {<br />JFrame frame = new JFrame("My Frame");<br />frame.setBounds(300, 300, 600, 400);<br />frame.setVisible(true);<br /> }<br />}<br />
    28. 28. Clojure Swing: Create a JFrame<br />(ns user<br /> (:import (javax.swingJFrame)))<br />(defn make-frame []<br /> (let [f (JFrame. "My Frame")]<br /> (.setBounds f 300 300 600 400)<br /> (.setVisible f true)<br /> f<br /> )<br /> )<br />f is the return value<br />
    29. 29. Alternative: Use doto<br />(defn make-frame []<br /> (let [f (JFrame. "My Frame")]<br /> (doto f<br /> (.setBounds 300 300 600 400)<br /> (.setVisible true))))<br />
    30. 30. Create a Panel & Button<br />(ns user<br /> (:import java.awt.FlowLayout<br /> (javax.swingJButtonJPanel)))<br />(defn make-panel []<br /> (let [panel (JPanel. (FlowLayout.))<br /> button (JButton. "Press Me")]<br /> (doto panel<br /> (.add button))))<br />
    31. 31. Make a Button do Something<br />(defn make-panel2 []<br /> (let [panel (JPanel. (FlowLayout.))<br /> button (JButton. "Press Me")]<br /> (.addActionListener button<br /> (proxy [ActionListener] []<br /> (actionPerformed [e] (println e))))<br /> (doto panel<br /> (.add button))<br /> )<br /> )<br />#<ActionEventjava.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Press Me...<br />
    32. 32. Clojure Custom Component<br />(defn make-component [msg]<br /> (proxy [javax.swing.JComponent] []<br /> (paintComponent [g]<br /> (let [height (.getHeight this)<br /> width (.getWidth this)]<br /> (doto g<br /> ...<br /> )))))<br />Detail on next slide<br />
    33. 33. Custom Component (cont/d)<br />(doto g<br /> (.setColorColor/gray)<br /> (.fillOval 20 20 (- width 20) (- height 20))<br /> (.setColorColor/yellow)<br /> (.fillOval 0 0 (- width 20) (- height 20))<br /> (.setFont (.deriveFont (.getFont g) (float 50)))<br /> (.setColorColor/black)<br /> (.drawStringmsg<br />(int (/ (- width (.stringWidth (.getFontMetrics g) msg)) 2))<br /> (int (/ height 2))))<br />
    34. 34. Three ways in which Clojure can help Swing<br />Reducing boiler-plate code<br />Easy to write code that generates the required patterns<br />Definitions of actions and easier binding<br />Easier to separate configuration (name, icon, keyboard shortcut, ...) from code hook<br />Flexibility and Reusability<br />Using functions as parameters for user customisation of behaviour<br />
    35. 35. 1. Reducing Boiler-Plate Code<br />GridBagConstraints c = new GridBagConstraints();<br />c.weighty = 1.0;<br />c.weightx = 1.0;<br />c.insets = new Insets(5, 5, 5, 5);<br />c.gridx = 0;<br />c.gridy = 0;<br />c.gridheight = 2;<br />c.anchor = GridBagConstraints.CENTER;<br />c.fill = GridBagConstraints.BOTH;<br /> add(leftListPane, c);<br />c.gridx = 1;<br />c.gridy = 0;<br />c.gridheight = 1;<br /> ...<br /><ul><li>GridBagConstraints are unwieldy
    36. 36. Use the same options a lot of the time
    37. 37. Difficult to understand</li></li></ul><li>Using a grid-bag-layout macro<br />(def panel<br /> (doto (JPanel. (GridBagLayout.))<br /> (grid-bag-layout<br /> :fill :BOTH, :insets (Insets. 5 5 5 5)<br /> :gridx 0, :gridy 0<br /> (JButton. "One")<br /> :gridy 1<br /> (JButton. "Two")<br /> :gridx 1, :gridy 0, :gridheight 2<br /> (JButton. "Three"))))<br />See http://stuartsierra.com/2010/01/05/taming-the-gridbaglayout<br />
    38. 38. 2. Defining Swing Actions<br />Swing Actions are a nice idea, but have problems. <br />Typically, you might have:<br />Lots of inner classes with repeated boiler plate code, or:<br />Separate classes that extend AbstractAction but are too tightly coupled to a main class so that they have the necessary context for the actionPerformed() method.<br />
    39. 39. Clojure Actions: Defer binding for actionPerformed method<br />With an Action in Clojure it’s possible to preset the ‘constant’ variables like Name, Icon, Accelerator ; but defer the binding for the handler.<br />This means we can easily separate the creation of an action according to some template from its binding to a response function.<br />
    40. 40. Create an Action when the handler function is known<br />(defmacro copy-action [handler]<br /> `(make-action <br /> {:name "Copy"<br /> :command-key "copy"<br /> :icon (ImageIcon. (fetch-image "copy.png"))<br /> :handler ~handler<br /> :mnemonic (mnemonic C)<br /> :accelerator (accelerator "ctrl C")}))<br />
    41. 41. 3. Flexibility and Reusability<br />(def *tracing-actions* true)<br /> <br />(defntrace-action [handler]<br />  (fn [#^ActionEvent e]<br />    (try<br />      (when *tracing-actions* <br />(print "Doing" (.getActionCommand e)))<br />      (handler e)<br />      (finally<br />        (when *tracing-actions* (println "Done"))))))<br />
    42. 42. Swing Worker & Busy Cursor<br />(defmacro with-busy-cursor<br /> [component f]<br /> `(proxy [SwingWorker] []<br /> (doInBackground []<br /> (.setCursor ~component (Cursor/getPredefinedCursor Cursor/WAIT_CURSOR))<br /> ~f)<br /> (done []<br /> (.setCursor ~component (Cursor/getDefaultCursor)))))<br />(with-busy-cursor chart<br /> (load-file data-file))<br />
    43. 43. Clojure/Swing in the Real World<br />
    44. 44. Creating a Chart Model<br />(defn make-model<br /> "Create and return a ChartModel using the supplied rows and picking out the x and y columns"<br /> [model-name rows #^String x-col #^String y-col]<br /> (let [model (DefaultChartModel. model-name)]<br /> (doseq [row rows]<br /> (let [x (get row x-col)<br /> y (get row y-col)]<br /> (when (and (number? x) (number? y))<br /> (.addPoint model (double x) (double y))))<br /> )<br /> model))<br />
    45. 45. Summary<br />Clojureis Powerful and Flexible<br />Excellent Java Interoperability<br />Opportunities to apply LISP power to Swing GUI development<br />Can be used for Real World Applications<br />A Secret Weapon for Productivity?<br />
    46. 46. Closure Example<br />(defnplusn [x]<br /> (fn [y] (+ x y)))<br />(def plus5 (plusn 5))<br />(plus5 3)<br />>> 8<br />

    ×