SlideShare uma empresa Scribd logo
1 de 27
Clojure




                   Clojure
          A practical LISP for the JVM


                          ¨
                Matthias Nußler

                m.nuessler@web.de


               February 1, 2011




                                         1 / 26
Clojure




Outline
          Introduction
          LISP
             LISP Quotes
          The Clojure Language
          Java Interoperability
             Calling Java from Clojure
             Calling Clojure from Java
          Concurrency
          IDE Support
          Questions & Answers
          Bibliography

                                         2 / 26
Clojure
   Introduction




What is Clojure?

          Clojure is
                  A fresh approach to LISP
                  A functional programming language
                  Created by Rich Hickey
                  Dynamically typed
                  Hosted on the Java Virtual Machine
                  Java interoperability is a design goal, rather than an
                  implementation detail
                  Strong concurrency semantics


                                                                           3 / 26
Clojure
   LISP




LISP

          LISt Processing (lists are a major data structure)
          Originally designed in 1958 by John McCarthy
          One of the oldest programming languages in existence
          (only Fortran is older)
          Once the favored programming language for AI research
          Based on lambda calculus
          Numerous LIPS dialects exist such as
              Scheme
              Common LISP
          “Lots of Irritating Superfluous Parentheses”?


                                                                  4 / 26
Clojure
   LISP
     LISP Quotes


LISP Quotes (1)



          “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


          “Lisp is a programmable programming language.”
          –John Foderaro: CACM, September 1991



                                                                             5 / 26
Clojure
   LISP
     LISP Quotes


LISP Quotes (2)


          “Greenspun’s Tenth Rule of Programming: any sufficiently
          complicated C or Fortran program contains an ad hoc
          informally-specified bug-ridden slow implementation of half of
          Common Lisp.”
          –Philip Greenspun


          “the greatest single programming language ever designed”
          –Alan Kay
          More quotes: http://www.paulgraham.com/quotes.html




                                                                          6 / 26
Clojure
   The Clojure Language




Clojure Language Basics
              “No syntax” :-)
              Prefix notation
              Lists are a core data structure in Clojure/LISP
              Code is written in the language’s own data-structures:
              (function param1 param2)
              Code as data philosophy
              Constants: Evaluate to themselves
              Symbols: Evaluate to the value bound to them (unless
              quoted)
              Bind a value to a symbol with def:
                     (def a-symbol 42) ; => #’user/a-symbol
                     a-symbol ; => 42
                     ’a-symbol ; => a-symbol
                                                                       7 / 26
Clojure
   The Clojure Language




Function definition


              fn creates an (anonymous) function object
                     Similar to lambda in Scheme (and Ruby)
                     (fn [x] (* x x))
                     Or even shorter using a macro: #(* %1 %1)
              Function object can be bound to a symbol
                     (def square (fn square [x] (* x x)))
                     (square 3) ; => 9
              Clojure provides a convenient shortcut
                     def plus fn → defn
                     (defn square [x] (* x x))



                                                                 8 / 26
Clojure
   The Clojure Language




Clojure Data Structures

          Data type       Example
          Numbers         1, 3.14, 3/4, ...
          Characters      a b c
          Strings         "a string" → Clojure strings are Java strings
          Regexps         #""
          Symbols         a b c
          Keywords        :default :key
          Lists           (1 2 3)
          Vectors         [1 2 3]
          Maps            {:a 1, :b 2, :c 3}
          Sets            #{"red" "green" "blue"}


                                                                          9 / 26
Clojure
   The Clojure Language




Higher Order Functions

          Higher order functions functions use functions as parameters or
          return values. Examples:
              every?
              filter
              map
              reduce
          Factorial using reduce
  1       (defn factorial [n]
  2         (let [ numbers ( range 1 (+ 1 n))]
  3           ( reduce * numbers )))



                                                                            10 / 26
Clojure
   Java Interoperability




Interoperability Overview

          With Clojure it is possible to
                Create instances of Java classes
                Invoke instance methods
                Invoke static methods on Java classes
                Implement Java interfaces, extend classes
                Generate Java classes and interfaces
                Compile Clojure code to Java byte code
                Call Clojure from Java
          → Access to thousands of Java libraries and frameworks


                                                                   11 / 26
Clojure
   Java Interoperability
      Calling Java from Clojure


Creating Instances



          Using the new special form

  1       ( import ’(java.text SimpleDateFormat ))
  2       (def sdf (new SimpleDateFormat " yyyy-MM-dd "))


          Shorter with dot notation
  3       (def sdf ( SimpleDateFormat . " yyyy-MM-dd "))




                                                            12 / 26
Clojure
   Java Interoperability
      Calling Java from Clojure


Member Access
          Invoking an instance method
  1       (defn date-from-string [ date-string ]
  2         (let [sdf ( SimpleDateFormat . " yyyy-MM-dd ")]
  3           (. parse sdf date-string )))


          Accessing a field
  4       (def point (java.awt. Point . 10 20))
  5       (.x point ) ; => 10


          Invoking static methods
  6       (Long/ parseLong " 12321 ")
  7       ( Thread / sleep 3000)

                                                              13 / 26
Clojure
   Java Interoperability
      Calling Java from Clojure


Method chaining



          Method chaining using dot-dot notation
  1       (.. ( Calendar / getInstance ) getTimeZone getDisplayName )


          That is equivalent to the following Java code
  2       Calendar . getInstance (). getTimezone ()
  3         . getDisplayName ();




                                                                   14 / 26
Clojure
   Java Interoperability
      Calling Java from Clojure


Calling multiple methods on a Java object


          Long version
  1       ( import ’(java.util Calendar ))
  2       (defn the-past-midnight-1 []
  3          (let [ calendar-obj ( Calendar / getInstance )]
  4            (. set calendar-obj Calendar / AM_PM Calendar /AM)
  5            (. set calendar-obj Calendar /HOUR 0)
  6            (. set calendar-obj Calendar / MINUTE 0)
  7            (. set calendar-obj Calendar / SECOND 0)
  8            (. set calendar-obj Calendar / MILLISECOND 0)
  9            (. getTime calendar-obj )))




                                                                    15 / 26
Clojure
   Java Interoperability
      Calling Java from Clojure


Calling multiple methods on a Java object


          Shorter using the doto macro

  1       (defn the-past-midnight-2 []
  2         (let [ calendar-obj ( Calendar / getInstance )]
  3           (doto calendar-obj
  4              (. set Calendar / AM_PM Calendar /AM)
  5              (. set Calendar /HOUR 0)
  6              (. set Calendar / MINUTE 0)
  7              (. set Calendar / SECOND 0)
  8              (. set Calendar / MILLISECOND 0))
  9           (. getTime calendar-obj )))




                                                              16 / 26
Clojure
   Java Interoperability
      Calling Java from Clojure


Implementing interfaces / extending classes



          With proxy

  1       (defn action-listener [idx frei buttons ]
  2         (proxy [java.awt. event . ActionListener ] []
  3           ( actionPerformed [e]
  4              (...))))




                                                            17 / 26
Clojure
   Java Interoperability
      Calling Clojure from Java


Calling Clojure from Java


  1       import clojure .lang.RT;
  2       import clojure .lang.Var;
  3
  4       public class Driver {
  5         public static void main( String [] args) throws Exceptio
  6           RT. loadResourceScript (" clojure_script .clj");
  7           Var report = RT.var("clj. script . examples ", " print-re
  8           Integer result = ( Integer ) report . invoke ("Siva");
  9           System .out. println ("[Java]    Result : " + result );
 10         }
 11       }



                                                                  18 / 26
Clojure
   Concurrency




Clojure’s Approach to Concurrency


             Immutable objects
             Persistent data-structures (preserve the previous version
             of themselves when modfied)
             Managed references (4 different kinds)
             Clojure programs are guaranteed not to deadlock
             Software Transactional Memory (STM) system
                 has ACI properties: atomicity, consistency, isolation (no
                 durability)
                 implements multiversion concurrency control (MVCC)




                                                                             19 / 26
Clojure
   Concurrency




Managed References



          Ref. type   Useful for
          ref         shared changes, synchronous, coordinated changes
          agent       shared changes, asynchronous, independent changes
          atom        shared changes, synchronous, independent changes
          var         isolated changes




                                                                    20 / 26
Clojure
   Concurrency




Refs, Agents, Atoms, Vars (1)


          Refs
             A ref holds a value that can be changed in a synchronous
             and coordinated manner
             Creating a ref: (def all-users (ref {}))
             Dereferencing a ref: (deref all-users)
             Mutating a ref using the ref-set, alter or commute
             functions
                 (ref-set all-users {})
                 STM transaction required!
                 Correct way: (dosync (ref-set all-users {}))



                                                                        21 / 26
Clojure
   Concurrency




Refs, Agents, Atoms, Vars (2)

          Agents
             Allow for asynchronous and independent changes to
             shared mutable data
             Hold values that can be changed using special functions
             (asynchronously, at some point in the future)

          Atoms
             Allow for synchronous and independent changes to
             mutable data
             Atoms are updated synchronously (immediately).


                                                                       22 / 26
Clojure
   Concurrency




Refs, Agents, Atoms, Vars (2)

          Agents
             Allow for asynchronous and independent changes to
             shared mutable data
             Hold values that can be changed using special functions
             (asynchronously, at some point in the future)

          Atoms
             Allow for synchronous and independent changes to
             mutable data
             Atoms are updated synchronously (immediately).


                                                                       22 / 26
Clojure
   Concurrency




Refs, Agents, Atoms, Vars (3)




          Vars
             Can be thought of as pointers to mutable storage locations,
             which can be updated on a per- thread basis
             Similar to java.lang.ThreadLocal




                                                                           23 / 26
Clojure
   IDE Support




IDE Support

                 Eclipse: Counterclockwise
                       http://code.google.com/p/counterclockwise/
                 IntelliJ IDEA: La Clojure
                       http://plugins.intellij.net/plugin/?id=4050
                 Netbeans: Enclojure
                       http://www.enclojure.org/
                 Emacs
                 Vim
                 Textmate
                 ...


                                                                     24 / 26
Clojure
   Questions & Answers




Questions?




          Source: http://xkcd.com/224/




                                         25 / 26
Clojure
   Bibliography




Bibliography




          Rathore, Amit: Clojure in Action
          MEAP Edition, Manning Publications, 2010

          Neppert, Burkhard: Clojure unter der Lupe
          Javamagazin 2/2011, Software & Support
          Media GmbH




                                                      26 / 26

Mais conteúdo relacionado

Mais procurados

Lecture 3: Storage and Variables
Lecture 3: Storage and VariablesLecture 3: Storage and Variables
Lecture 3: Storage and VariablesEelco Visser
 
Wrapper induction construct wrappers automatically to extract information f...
Wrapper induction   construct wrappers automatically to extract information f...Wrapper induction   construct wrappers automatically to extract information f...
Wrapper induction construct wrappers automatically to extract information f...George Ang
 
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...Shinpei Hayashi
 
Introduction to Chainer
Introduction to ChainerIntroduction to Chainer
Introduction to ChainerShunta Saito
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manualLaura Popovici
 
Caffe framework tutorial2
Caffe framework tutorial2Caffe framework tutorial2
Caffe framework tutorial2Park Chunduck
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowOswald Campesato
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Itzik Kotler
 
Lenar Gabdrakhmanov (Provectus): Speech synthesis
Lenar Gabdrakhmanov (Provectus): Speech synthesisLenar Gabdrakhmanov (Provectus): Speech synthesis
Lenar Gabdrakhmanov (Provectus): Speech synthesisProvectus
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVMMario Fusco
 
Attention mechanisms with tensorflow
Attention mechanisms with tensorflowAttention mechanisms with tensorflow
Attention mechanisms with tensorflowKeon Kim
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures CodingMax Kleiner
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manualnahalomar
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scopesuthi
 
Configuring Mahout Clustering Jobs - Frank Scholten
Configuring Mahout Clustering Jobs - Frank ScholtenConfiguring Mahout Clustering Jobs - Frank Scholten
Configuring Mahout Clustering Jobs - Frank Scholtenlucenerevolution
 
Introduction to Deep Learning with Python
Introduction to Deep Learning with PythonIntroduction to Deep Learning with Python
Introduction to Deep Learning with Pythonindico data
 

Mais procurados (20)

Lecture 3: Storage and Variables
Lecture 3: Storage and VariablesLecture 3: Storage and Variables
Lecture 3: Storage and Variables
 
Wrapper induction construct wrappers automatically to extract information f...
Wrapper induction   construct wrappers automatically to extract information f...Wrapper induction   construct wrappers automatically to extract information f...
Wrapper induction construct wrappers automatically to extract information f...
 
Kotlin
KotlinKotlin
Kotlin
 
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
 
Introduction to Chainer
Introduction to ChainerIntroduction to Chainer
Introduction to Chainer
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Caffe framework tutorial2
Caffe framework tutorial2Caffe framework tutorial2
Caffe framework tutorial2
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlow
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
 
Lenar Gabdrakhmanov (Provectus): Speech synthesis
Lenar Gabdrakhmanov (Provectus): Speech synthesisLenar Gabdrakhmanov (Provectus): Speech synthesis
Lenar Gabdrakhmanov (Provectus): Speech synthesis
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Attention mechanisms with tensorflow
Attention mechanisms with tensorflowAttention mechanisms with tensorflow
Attention mechanisms with tensorflow
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures Coding
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manual
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
 
Ns2
Ns2Ns2
Ns2
 
Configuring Mahout Clustering Jobs - Frank Scholten
Configuring Mahout Clustering Jobs - Frank ScholtenConfiguring Mahout Clustering Jobs - Frank Scholten
Configuring Mahout Clustering Jobs - Frank Scholten
 
Introduction to Deep Learning with Python
Introduction to Deep Learning with PythonIntroduction to Deep Learning with Python
Introduction to Deep Learning with Python
 

Semelhante a Clojure - A practical LISP for the JVM

Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Paddy Lock
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
Clojure and The Robot Apocalypse
Clojure and The Robot ApocalypseClojure and The Robot Apocalypse
Clojure and The Robot Apocalypseelliando dias
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
Clojure Interoperability
Clojure InteroperabilityClojure Interoperability
Clojure Interoperabilityrik0
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
DevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingDevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingHenri Tremblay
 
Reactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptLuka Jacobowitz
 
TDC2016POA | Trilha Programacao Funcional - Considere usar Clojure/ClojureScr...
TDC2016POA | Trilha Programacao Funcional - Considere usar Clojure/ClojureScr...TDC2016POA | Trilha Programacao Funcional - Considere usar Clojure/ClojureScr...
TDC2016POA | Trilha Programacao Funcional - Considere usar Clojure/ClojureScr...tdc-globalcode
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming LanguageYLTO
 
Introduction to Clojure
Introduction to ClojureIntroduction to Clojure
Introduction to ClojureRenzo Borgatti
 
Indic threads pune12-polyglot & functional programming on jvm
Indic threads pune12-polyglot & functional programming on jvmIndic threads pune12-polyglot & functional programming on jvm
Indic threads pune12-polyglot & functional programming on jvmIndicThreads
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java introkabirmahlotra
 

Semelhante a Clojure - A practical LISP for the JVM (20)

Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
Clojure and The Robot Apocalypse
Clojure and The Robot ApocalypseClojure and The Robot Apocalypse
Clojure and The Robot Apocalypse
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
Seeking Clojure
Seeking ClojureSeeking Clojure
Seeking Clojure
 
Clojure Interoperability
Clojure InteroperabilityClojure Interoperability
Clojure Interoperability
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
DevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingDevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programming
 
Reactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScript
 
TDC2016POA | Trilha Programacao Funcional - Considere usar Clojure/ClojureScr...
TDC2016POA | Trilha Programacao Funcional - Considere usar Clojure/ClojureScr...TDC2016POA | Trilha Programacao Funcional - Considere usar Clojure/ClojureScr...
TDC2016POA | Trilha Programacao Funcional - Considere usar Clojure/ClojureScr...
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming Language
 
Introduction to Clojure
Introduction to ClojureIntroduction to Clojure
Introduction to Clojure
 
Java 8 고급 (6/6)
Java 8 고급 (6/6)Java 8 고급 (6/6)
Java 8 고급 (6/6)
 
Indic threads pune12-polyglot & functional programming on jvm
Indic threads pune12-polyglot & functional programming on jvmIndic threads pune12-polyglot & functional programming on jvm
Indic threads pune12-polyglot & functional programming on jvm
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java intro
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Clojure - A practical LISP for the JVM

  • 1. Clojure Clojure A practical LISP for the JVM ¨ Matthias Nußler m.nuessler@web.de February 1, 2011 1 / 26
  • 2. Clojure Outline Introduction LISP LISP Quotes The Clojure Language Java Interoperability Calling Java from Clojure Calling Clojure from Java Concurrency IDE Support Questions & Answers Bibliography 2 / 26
  • 3. Clojure Introduction What is Clojure? Clojure is A fresh approach to LISP A functional programming language Created by Rich Hickey Dynamically typed Hosted on the Java Virtual Machine Java interoperability is a design goal, rather than an implementation detail Strong concurrency semantics 3 / 26
  • 4. Clojure LISP LISP LISt Processing (lists are a major data structure) Originally designed in 1958 by John McCarthy One of the oldest programming languages in existence (only Fortran is older) Once the favored programming language for AI research Based on lambda calculus Numerous LIPS dialects exist such as Scheme Common LISP “Lots of Irritating Superfluous Parentheses”? 4 / 26
  • 5. Clojure LISP LISP Quotes LISP Quotes (1) “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 “Lisp is a programmable programming language.” –John Foderaro: CACM, September 1991 5 / 26
  • 6. Clojure LISP LISP Quotes LISP Quotes (2) “Greenspun’s Tenth Rule of Programming: any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp.” –Philip Greenspun “the greatest single programming language ever designed” –Alan Kay More quotes: http://www.paulgraham.com/quotes.html 6 / 26
  • 7. Clojure The Clojure Language Clojure Language Basics “No syntax” :-) Prefix notation Lists are a core data structure in Clojure/LISP Code is written in the language’s own data-structures: (function param1 param2) Code as data philosophy Constants: Evaluate to themselves Symbols: Evaluate to the value bound to them (unless quoted) Bind a value to a symbol with def: (def a-symbol 42) ; => #’user/a-symbol a-symbol ; => 42 ’a-symbol ; => a-symbol 7 / 26
  • 8. Clojure The Clojure Language Function definition fn creates an (anonymous) function object Similar to lambda in Scheme (and Ruby) (fn [x] (* x x)) Or even shorter using a macro: #(* %1 %1) Function object can be bound to a symbol (def square (fn square [x] (* x x))) (square 3) ; => 9 Clojure provides a convenient shortcut def plus fn → defn (defn square [x] (* x x)) 8 / 26
  • 9. Clojure The Clojure Language Clojure Data Structures Data type Example Numbers 1, 3.14, 3/4, ... Characters a b c Strings "a string" → Clojure strings are Java strings Regexps #"" Symbols a b c Keywords :default :key Lists (1 2 3) Vectors [1 2 3] Maps {:a 1, :b 2, :c 3} Sets #{"red" "green" "blue"} 9 / 26
  • 10. Clojure The Clojure Language Higher Order Functions Higher order functions functions use functions as parameters or return values. Examples: every? filter map reduce Factorial using reduce 1 (defn factorial [n] 2 (let [ numbers ( range 1 (+ 1 n))] 3 ( reduce * numbers ))) 10 / 26
  • 11. Clojure Java Interoperability Interoperability Overview With Clojure it is possible to Create instances of Java classes Invoke instance methods Invoke static methods on Java classes Implement Java interfaces, extend classes Generate Java classes and interfaces Compile Clojure code to Java byte code Call Clojure from Java → Access to thousands of Java libraries and frameworks 11 / 26
  • 12. Clojure Java Interoperability Calling Java from Clojure Creating Instances Using the new special form 1 ( import ’(java.text SimpleDateFormat )) 2 (def sdf (new SimpleDateFormat " yyyy-MM-dd ")) Shorter with dot notation 3 (def sdf ( SimpleDateFormat . " yyyy-MM-dd ")) 12 / 26
  • 13. Clojure Java Interoperability Calling Java from Clojure Member Access Invoking an instance method 1 (defn date-from-string [ date-string ] 2 (let [sdf ( SimpleDateFormat . " yyyy-MM-dd ")] 3 (. parse sdf date-string ))) Accessing a field 4 (def point (java.awt. Point . 10 20)) 5 (.x point ) ; => 10 Invoking static methods 6 (Long/ parseLong " 12321 ") 7 ( Thread / sleep 3000) 13 / 26
  • 14. Clojure Java Interoperability Calling Java from Clojure Method chaining Method chaining using dot-dot notation 1 (.. ( Calendar / getInstance ) getTimeZone getDisplayName ) That is equivalent to the following Java code 2 Calendar . getInstance (). getTimezone () 3 . getDisplayName (); 14 / 26
  • 15. Clojure Java Interoperability Calling Java from Clojure Calling multiple methods on a Java object Long version 1 ( import ’(java.util Calendar )) 2 (defn the-past-midnight-1 [] 3 (let [ calendar-obj ( Calendar / getInstance )] 4 (. set calendar-obj Calendar / AM_PM Calendar /AM) 5 (. set calendar-obj Calendar /HOUR 0) 6 (. set calendar-obj Calendar / MINUTE 0) 7 (. set calendar-obj Calendar / SECOND 0) 8 (. set calendar-obj Calendar / MILLISECOND 0) 9 (. getTime calendar-obj ))) 15 / 26
  • 16. Clojure Java Interoperability Calling Java from Clojure Calling multiple methods on a Java object Shorter using the doto macro 1 (defn the-past-midnight-2 [] 2 (let [ calendar-obj ( Calendar / getInstance )] 3 (doto calendar-obj 4 (. set Calendar / AM_PM Calendar /AM) 5 (. set Calendar /HOUR 0) 6 (. set Calendar / MINUTE 0) 7 (. set Calendar / SECOND 0) 8 (. set Calendar / MILLISECOND 0)) 9 (. getTime calendar-obj ))) 16 / 26
  • 17. Clojure Java Interoperability Calling Java from Clojure Implementing interfaces / extending classes With proxy 1 (defn action-listener [idx frei buttons ] 2 (proxy [java.awt. event . ActionListener ] [] 3 ( actionPerformed [e] 4 (...)))) 17 / 26
  • 18. Clojure Java Interoperability Calling Clojure from Java Calling Clojure from Java 1 import clojure .lang.RT; 2 import clojure .lang.Var; 3 4 public class Driver { 5 public static void main( String [] args) throws Exceptio 6 RT. loadResourceScript (" clojure_script .clj"); 7 Var report = RT.var("clj. script . examples ", " print-re 8 Integer result = ( Integer ) report . invoke ("Siva"); 9 System .out. println ("[Java] Result : " + result ); 10 } 11 } 18 / 26
  • 19. Clojure Concurrency Clojure’s Approach to Concurrency Immutable objects Persistent data-structures (preserve the previous version of themselves when modfied) Managed references (4 different kinds) Clojure programs are guaranteed not to deadlock Software Transactional Memory (STM) system has ACI properties: atomicity, consistency, isolation (no durability) implements multiversion concurrency control (MVCC) 19 / 26
  • 20. Clojure Concurrency Managed References Ref. type Useful for ref shared changes, synchronous, coordinated changes agent shared changes, asynchronous, independent changes atom shared changes, synchronous, independent changes var isolated changes 20 / 26
  • 21. Clojure Concurrency Refs, Agents, Atoms, Vars (1) Refs A ref holds a value that can be changed in a synchronous and coordinated manner Creating a ref: (def all-users (ref {})) Dereferencing a ref: (deref all-users) Mutating a ref using the ref-set, alter or commute functions (ref-set all-users {}) STM transaction required! Correct way: (dosync (ref-set all-users {})) 21 / 26
  • 22. Clojure Concurrency Refs, Agents, Atoms, Vars (2) Agents Allow for asynchronous and independent changes to shared mutable data Hold values that can be changed using special functions (asynchronously, at some point in the future) Atoms Allow for synchronous and independent changes to mutable data Atoms are updated synchronously (immediately). 22 / 26
  • 23. Clojure Concurrency Refs, Agents, Atoms, Vars (2) Agents Allow for asynchronous and independent changes to shared mutable data Hold values that can be changed using special functions (asynchronously, at some point in the future) Atoms Allow for synchronous and independent changes to mutable data Atoms are updated synchronously (immediately). 22 / 26
  • 24. Clojure Concurrency Refs, Agents, Atoms, Vars (3) Vars Can be thought of as pointers to mutable storage locations, which can be updated on a per- thread basis Similar to java.lang.ThreadLocal 23 / 26
  • 25. Clojure IDE Support IDE Support Eclipse: Counterclockwise http://code.google.com/p/counterclockwise/ IntelliJ IDEA: La Clojure http://plugins.intellij.net/plugin/?id=4050 Netbeans: Enclojure http://www.enclojure.org/ Emacs Vim Textmate ... 24 / 26
  • 26. Clojure Questions & Answers Questions? Source: http://xkcd.com/224/ 25 / 26
  • 27. Clojure Bibliography Bibliography Rathore, Amit: Clojure in Action MEAP Edition, Manning Publications, 2010 Neppert, Burkhard: Clojure unter der Lupe Javamagazin 2/2011, Software & Support Media GmbH 26 / 26