SlideShare a Scribd company logo
(first '(Clojure.))
Clojure is

A dynamic,

LISP-based

programming language

running on the JVM
Origin



2007, Rich Hickey

.. 1958, John McCarthy
Features


Functional

Homoiconic

Immutability
Plus


Concurrency

Pragmatism

Java Interop
Fun!
Syntax
Homoiconic

(+ 1 1)

● Uniform Prefix Notation
● List Processing (LISP)

● Code is Data




=> Predictable!
Scalars
c        ; characters
"Hello"   ; strings

42        ; numbers
3/2       ; ratios

true      ; booleans

nil
Names

; symbols          ; keywords

i                  :name
println            :when
+
empty?
next-state
.toUpperCase
Collections
Lists



(println "Hello")

(first '(println "Hello"))
Vectors




["bag" "of" 4 "chips"]
Hash-maps



{:name "Intro"
 :date "2012-05-29"}
Sets




#{"unique" "snowflakes"}
Special Forms
Define




(def i 1)
If



(if true
  (/ 1 1)
  (/ 1 0))
Functions



(fn [name]
  (str "Hello " name "!"))
Named Functions



(def greet (fn [name]
             (str "Hello " name)))
The defn macro



(defn greet [name]
  (str "Hello " name))
Let the local names in


(defn greet [name]
  (let [greeting "Hello"
        out (str greeting " " name)]
    out))
Sugared Lambdas


#(str %1 %2)

; same as
(fn [a1 a2] (str a1 a2))
The rest is just
  eval/apply
Basic Usage

 => represents results
Vectors
(def items [1 2 3])

(first items)
=> 1

(rest items)
=> (2 3)

(items 0)
=> 1
Adding to collections


(cons items [3 4])
=> [1 2 3 4]

(conj items 3)
=> [1 2 3]
Map/Reduce


(map #(+ % 1) [1 2 3])
=> (2 3 4)

(reduce #(- %1 %2) [1 2 3])
=> -4
For Comprehension


(for [i (range 1 7) :when (even? i)]
  (str "item-" i)))

=> ("item-2" "item-4" "item-6")
Composing Data
Constructs
(def persons [{:id 1
               :name "Some Body"}
              {:id 2
               :name "Some Other"}])

(let [person (persons 0)]
  (person :name))

=> "Some Body"
The key is getting the value


(:name (first persons))
=> "Some Body"

(map :name persons)
=> ("Some Body" "Some Other")
Records


(defrecord Person [id name])

(let [person (Person. 1 "Some Body")]
  (:name person))

=> "Some Body"
Destructuring


(let [{id :id name :name} person]
  [id name])

=> [1 "Some Body"]
Compose Data, Compose Functions

Data first

Collections

Flow

Abstractions
Concurrency
States over Time


Value as State

Reference to Identity

Identity over Time
Atoms
(def item-counter (atom 0))

(defn next-item []
  (str "item-"
       (swap! item-counter inc)))

(next-item)
=> "item-1"
(next-item)
=> "item-2"
...
Refs

(def item1 (ref {:a "foo"}))
(def item2 (ref {:a "bar"}))

(let [v1 (:a @item1) v2 (:a @item2)]
  (dosync
    (alter item1 assoc :a v2)
    (alter item2 assoc :a v1)))
Agents

(def info (agent {}))

(send info assoc :status :open)

; eventually,
; (assoc info :status :open)
; is called
Java Interop
Working with Monsters


Can be shackled by parentheses,

even fed immutability,

but their nature is wild
Parallel HTTP Fetches



(ns parallel-fetch
  (:import (java.io InputStream InputStreamReader BufferedReader)
          (java.net URL HttpURLConnection)))
(defn get-url [url]
  (let [conn (doto (.openConnection (URL. url))
               (.setRequestMethod "GET")
               (.connect))]
    (with-open [stream (BufferedReader.
                         (InputStreamReader.
                            (.getInputStream conn)))]
      (.toString (reduce #(.append %1 %2)
                          (StringBuffer.) (line-seq stream))))))
(defn get-urls [urls]
  (let [agents (doall (map #(agent %) urls))]
    (doseq [agent agents] (send-off agent get-url))
    (apply await-for 5000 agents)
    (doall (map #(deref %) agents))))

(prn (get-urls ["http://erlang.org" "http://clojure.org/"]))
Interface On Your Own
         Terms
Idiom


(get-name root)

(get-attr link "href")

(get-child-elements div)
Protocol


(defprotocol DomAccess
  (get-name [this])
  (get-attr [this attr-name])
  (get-child-elements [this]))
Realization

(extend-type org.w3c.dom.Node
  DomAccess

 (get-name [this] (.getNodeName this))

 (get-attr [this attr-name]
   (if (.hasAttribute this attr-name)
     (.getAttribute this attr-name)))

 (get-child-elements [this]
   (filter #(= (.getNodeType %1) Node/ELEMENT_NODE)
           (node-list (.getChildNodes this)))))
Working with Clojure
Leiningen

$ lein deps

$ lein compile

$ lein repl

$ lein uberjar

$ lein ring server-headless
Editors


Vim: VimClojure

Emacs: Swank

IDEA: La Clojure
More Info

<http://clojure.org/>

<http://clojure.org/cheatsheet>

<http://clojuredocs.org/>

<http://dev.clojure.org/display/community/Clojure+Success+Stories>

<http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hickey>

<http://www.infoq.com/presentations/Simple-Made-Easy>
Have Fun!
(thanks!)
@niklasl

@valtechSweden
Attribution



● Clojure Logo © Rich Hickey
● Playing Ball

● "Where the Wild Things Are" © Maurice Sendak

● Parallel HTTP Fetches by Will Larson

More Related Content

PDF
Refactoring to Macros with Clojure
PPTX
Poor Man's Functional Programming
PDF
はじめてのGroovy
PDF
Groovy ネタ NGK 忘年会2009 ライトニングトーク
PDF
Python postgre sql a wonderful wedding
PDF
"PostgreSQL and Python" Lightning Talk @EuroPython2014
PDF
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
PPTX
Grails queries
Refactoring to Macros with Clojure
Poor Man's Functional Programming
はじめてのGroovy
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Python postgre sql a wonderful wedding
"PostgreSQL and Python" Lightning Talk @EuroPython2014
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
Grails queries

What's hot (19)

PDF
Elm: give it a try
PPTX
Psycopg2 - Connect to PostgreSQL using Python Script
PDF
Programming with Python and PostgreSQL
PDF
Using Scala Slick at FortyTwo
PDF
Cycle.js: Functional and Reactive
PDF
여자개발자모임터 6주년 개발 세미나 - Scala Language
PPT
JDBC Core Concept
KEY
Template Haskell とか
PDF
Mozilla とブラウザゲーム
PDF
Ramda, a functional JavaScript library
PPTX
ES6 in Real Life
PDF
groovy databases
PDF
Miracle of std lib
PPT
An Elephant of a Different Colour: Hack
PPTX
2017 02-07 - elastic & spark. building a search geo locator
PDF
360|iDev
KEY
Invertible-syntax 入門
KEY
groovy & grails - lecture 3
PDF
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Elm: give it a try
Psycopg2 - Connect to PostgreSQL using Python Script
Programming with Python and PostgreSQL
Using Scala Slick at FortyTwo
Cycle.js: Functional and Reactive
여자개발자모임터 6주년 개발 세미나 - Scala Language
JDBC Core Concept
Template Haskell とか
Mozilla とブラウザゲーム
Ramda, a functional JavaScript library
ES6 in Real Life
groovy databases
Miracle of std lib
An Elephant of a Different Colour: Hack
2017 02-07 - elastic & spark. building a search geo locator
360|iDev
Invertible-syntax 入門
groovy & grails - lecture 3
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Ad

Viewers also liked (8)

PDF
Lee Stevens sharepoint 2010
PPTX
#SMiLELondon Pearson
PDF
Groovy Fly Through
PPT
تويتر لاستخدام التواصل الاجتماعي
ODP
Something Specific and Simple
PDF
Blog & Electronic Press التدوين و الصحافة الإلكترونية
PDF
Länkad Data
PDF
University Ready? Task 2 - Reading Like You've Never Read Before
Lee Stevens sharepoint 2010
#SMiLELondon Pearson
Groovy Fly Through
تويتر لاستخدام التواصل الاجتماعي
Something Specific and Simple
Blog & Electronic Press التدوين و الصحافة الإلكترونية
Länkad Data
University Ready? Task 2 - Reading Like You've Never Read Before
Ad

Similar to (first '(Clojure.)) (20)

KEY
Clojure Intro
PDF
Pune Clojure Course Outline
PDF
Clojure class
ODP
Clojure basics
KEY
(map Clojure everyday-tasks)
PDF
Clojure - A new Lisp
PDF
Introduction to clojure
ODP
Clojure: Practical functional approach on JVM
ODP
Getting started with Clojure
ODP
Clojure made simple - Lightning talk
PDF
Continuation Passing Style and Macros in Clojure - Jan 2012
PDF
Clojure: Simple By Design
PDF
Clojure - An Introduction for Lisp Programmers
PPTX
Clojure 7-Languages
PDF
Clojure A Dynamic Programming Language for the JVM
PDF
Clojure
PDF
Clojure 1.1 And Beyond
PDF
Fun with Functional Programming in Clojure
PDF
Clojure made-simple - John Stevenson
PDF
The Magnificent Seven
Clojure Intro
Pune Clojure Course Outline
Clojure class
Clojure basics
(map Clojure everyday-tasks)
Clojure - A new Lisp
Introduction to clojure
Clojure: Practical functional approach on JVM
Getting started with Clojure
Clojure made simple - Lightning talk
Continuation Passing Style and Macros in Clojure - Jan 2012
Clojure: Simple By Design
Clojure - An Introduction for Lisp Programmers
Clojure 7-Languages
Clojure A Dynamic Programming Language for the JVM
Clojure
Clojure 1.1 And Beyond
Fun with Functional Programming in Clojure
Clojure made-simple - John Stevenson
The Magnificent Seven

Recently uploaded (20)

PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
Teaching material agriculture food technology
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
August Patch Tuesday
PPTX
Tartificialntelligence_presentation.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
A Presentation on Artificial Intelligence
PDF
Machine learning based COVID-19 study performance prediction
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Getting Started with Data Integration: FME Form 101
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
A comparative study of natural language inference in Swahili using monolingua...
Assigned Numbers - 2025 - Bluetooth® Document
Heart disease approach using modified random forest and particle swarm optimi...
Empathic Computing: Creating Shared Understanding
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Teaching material agriculture food technology
MIND Revenue Release Quarter 2 2025 Press Release
August Patch Tuesday
Tartificialntelligence_presentation.pptx
Network Security Unit 5.pdf for BCA BBA.
A Presentation on Artificial Intelligence
Machine learning based COVID-19 study performance prediction
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Getting Started with Data Integration: FME Form 101
TLE Review Electricity (Electricity).pptx
Spectroscopy.pptx food analysis technology
Spectral efficient network and resource selection model in 5G networks
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
A comparative study of natural language inference in Swahili using monolingua...

(first '(Clojure.))