SlideShare une entreprise Scribd logo
1  sur  57
Introduction to Clojure


          Soligorsk, 26.01.2013
          Friedrich Boeckh
Clojure rocks & Sam Aaron is badass
Overtone,
http://blip.tv/clojure/sam-aaron-programming-music-with-overtone-5970273
ThoughtWorks 2012:
               Clojure is on the Radar
http://www.thoughtworks.com/articles
/technology-radar-october-2012




                                                  … even Microsoft cares




                                        … as always - it does not make
                                        everybody happy:
                                       http://cafe.elharo.com/programming/java-
                                       programming/why-functional-programming-in-java-is-
                                       dangerous/
World singles
Sean Corfield
http://corfield.org/articles/WorldSinglesWeb.pdf




                                                    • 3,000,000 members
                                       • 1,000,000 emails / day
                                       • 80,000 logins / day
                                       • 2,000 concurrent users (average)
uSwitch.com
http://skillsmatter.com/podcast/home/reviving-the-uswitch-back-office-with-clojure




                                                       Ryan Greenhall
Clojure at a bank
Malcolm Sparks
http://blog.malcolmsparks.com/?p=17
Clojure at another bank
Jon Pither
http://www.pitheringabout.com/?p=693
Clojure at yet another bank
Clojure at Nokia Entertainment




http://skillsmatter.com/event/clojure/clojure-at-nokia-entertainment
Big Data Done Better – Mastodon C




                   https://www.mastodonc.com/
Clojure gives Innovation a Boost




Stuart Halloway   Justin Gethland
                  & Rich Hickey
Russian wording in the following
                               from Alex Ott´s talk at itsea 2012
http://de.slideshare.net/alexott/clojure-lisp-for-the-modern-world
http://alexott.net/ru/clojure/clojure-intro/index.html
http://alexott.net/en/clojure/video.html
Что такое Clojure?
• Rich Hickey, 17.10.2007, с v1.4, RC v1.5
• Lisp-ообразный
• Функциональный
• Конкурентное программирование
   http://stackoverflow.com/questions/1050222/concurrency-vs-
   parallelism-what-is-the-difference
• Многоплатформенный (JVM, .Net, JavaScript, etc.)
• Открытый исходный код и либеральная лицензия
   Eclipse Public License 1.0
• Активное сообщество разработчиков
• Коммерческое применение
• Коммерческая поддержка
Активное сообщество разработчиков




Sean Corfield
http://corfield.org/articles/WorldSinglesWeb.pdf, mid 2012
Почему Lisp?

• Простой синтаксис - code as data structures homoiconic
• Метапрограммирование (макросы)
   • Создание доменно-специфических языков DSLs
   • Генерация кода во время компиляции
   • Возможность избежать повторений
• Генерация и выполнение кода в runtime
• Интерактивная разработка REPL
• Динамически типизированный
Lisp? 7 элементов + fn нотация




    John McCarthy
      1927 - 2011
Lisp Specification, 1958
Lisp? 7 элементов + fn нотация
Paul Graham, The Roots of Lisp
http://www.paulgraham.com/rootsoflisp.html
http://www.cse.sc.edu/~mgv/csce531sp07/jmc.pdf
• (quote x) returns x
• (atom x)returns the atom t (true) if the value of x is
   an atom or the empty list. Otherwise it returns ().
• (eq x y) returns t if the values of x and y are the
   same atom or both the empty list, and () otherwise.
• (car x) expects the value of x to be a list, and returns its first element.
• (cdr x) expects the value of x to be a list, and returns everything after
  the first element.
• (cons x y) expects the value of y to be a list, and returns a list
  containing the value of x followed by the elements of the value of y.
• (cond (p1 e1) ... (pn en)) is evaluated as follows. The p
  expressions are evaluated in order until one returns t (true). When one is
  found, the value of the corresponding e expression is returned as the value
  of the whole cond expression.
• A function is expressed as (lambda (p1 ... pn) e), where
  p1 ... pn are atoms, called parameters, and e is an expression.
Богатство Lisp наследия
• Hal Abelson, Jerry Sussman and Julie Sussman, Structure and
  Interpretation of Computer Programs (SICP),
  http://mitpress.mit.edu/sicp/,
  http://newstar.rinet.ru/~goga/sicp/sicp.pdf (russ.),
  http://ocw.mit.edu/courses/electrical-engineering-and-
  computer-science/6-001-structure-and-interpretation-of-
  computer-programs-spring-2005/video-lectures/

• Peter Seibel, Practical Common Lisp,
  http://www.gigamonkeys.com/book/


• Paul Graham, On Lisp, http://www.paulgraham.com/onlisp.html,
  http://lib.store.yahoo.net/lib/paulgraham/onlisp.pdf
Богатство Lisp наследия




                              Conrad Barski (M.D.)


                          http://vimeo.com/9605639
Богатство Lisp наследия
• VLSI design, Boeing, US government & military, ITA Software (in
  2010 acquired by Google)

• NASA, The Remote Agent Experiment - Debugging code from
  60 million miles away, Ron Garret, 14 February 2012

• Paul Graham, Beating the Averages,
  http://www.paulgraham.com/avg.html,
  http://lib.store.yahoo.net/lib/paulgraham/bbnexcerpts.txt

• Andreas Lehmann, Common Lisp Raytracer, (source code
  transcript e. g. here https://github.com/fbmnds/clrt),
  videos and PDFs
  http://rudairandamacha.blogspot.de/2012/09/writing-simple-
  raytracer-in-common-lisp.html
Богатство Lisp наследия
• Peter Norvig, Paradigms of Artificial Intelligence Programming:
  Case Studies in Common Lisp (PAIP),
  http://norvig.com/paip.html

• Daniel P. Friedman, Matthias Felleisen, The Little Schemer,
  http://mitpress.mit.edu/books/little-schemer

• Overview by Vsevolod Dyomkin,
  http://lisp-univ-etc.blogspot.com/2012/12/lisp-books.html

• Rich Hickey, Books that influenced Clojure,
  http://www.amazon.com/gp/richpub/listmania/fullview/R3LG3Z
  BZS4GCTH
Богатство Lisp наследия – Emacs ??
Marco Baringer's SLIME Tutorial Video:




                 http://www.youtube.com/watch?v=_B_4vhsmRRI
                                                 (   underscore)
Отличия от других Lisp’ов
• Немного упрощенный синтаксис -- меньше скобочек
• Неизменяемые данные (immutability)
• Добавлено больше базовых структур данных: вектора,
  отображения (maps) и т.д.
• Расширяемый reader, но без reader macros
• "Ленивые" коллекции (lazy-seq)
• Мета-информация привязанная к данным и функциям
• Case-sensitive names
• Исключения вместо условий/рестартов
• Полиморфизм: протоколы и мультиметоды
• Software Transactional Memory System (STM)
• Java Interoperation, http://clojure.org/java_interop
                                        (   underscore)
Полиморфизм на Clojure
  • Протоколы, мультиметоды




           …

Stuart Sierra, https://www.ibm.com/developerworks/java/library/j-clojure-protocols/
Полиморфизм на Clojure
• Протоколы, мультиметоды




http://oredev.org/2012/sessions/expressing-yourself-polymorphism-in-clojure
Software Transactional Memory System (STM)




                                  Graig Andera
 http://pluralsight.com/training/Courses/TableOfContents/clojure-concurrency-tutorial
Почему ФП?

• Функции в математическом смысле
   Lambda Calculus
• Функции – объекты первого порядка
   first-class objects, higher-order functions (HOF)
• Неизменяемость данных immutability
   • Отсутствие побочных эффектов
   • Возможность автоматической параллелизации кода
   • Меньше проблем с конкурентным выполнением кода
Lambda Calculus ~ “effectively programmable”




  Alonzo Church   Stephen Kleene   Alan Turing
   1903 - 1995      1909 - 1994    1912 - 1954
Lambda Calculus
http://www.infoq.com/presentations/Y-Combinator



(defn Y
  [h]
                                 Jim Weirich (Y-rich)
  ((fn [f] (f f)) (fn [f]
                    (h (fn [n]
                          ((f f) n))))))

(def fact
     (Y (fn [g]
          (fn [n]
            (if (< n 2) 1 (* n (g (dec n))))))))
transcript by Michael Kohl,
http://citizen428.net/blog/2010/12/14/clojure-deriving-the-y-combinator-in-7-stolen-steps/
Почему ФП?




             1922 - 1990



                 You want functions?
Почему ФП?

Get some:
Clojure / ФП - Namespaces
http://clojure.org/namespaces

• Namespaces are mappings from simple (unqualified) symbols
  to Vars and/or Classes.
• Namespaces are first-class, they can be enumerated etc.
• Namespaces are also dynamic, they can be created, removed
  and modified at runtime, at the Repl etc.
• The best way to set up a new namespace at the top of a Clojure
  source file is to use the ns macro.
• The current namespace, *ns* can and should be set only with
  a call to in-ns or the ns macro, both of which create the
  namespace if it doesn't exist.
Clojure / ФП - Namespaces
• clojure.core - Fundamental library of the Clojure language
• clojure.data - Non-core data functions.
• clojure.inspector - Graphical object inspector for Clojure data
  structures.
• clojure.java.browse - Start a web browser from Clojure
• clojure.java.io
• clojure.java.javadoc - A repl helper to quickly open javadocs.
• clojure.java.shell
• clojure.main
• clojure.pprint - A Pretty Printer for Clojure
• clojure.reflect - Reflection on Host Types
• clojure.repl - Utilities meant to be used interactively at the REPL
Clojure / ФП - Namespaces
• clojure.set
• clojure.stacktrace - Print stack traces oriented towards Clojure, not
  Java.
• clojure.string
• clojure.template - Macros that expand to repeated copies of a
  template expression.
• clojure.test - A unit testing framework.
• clojure.walk
• clojure.xml - XML reading/writing.
• clojure.zip - Functional hierarchical zipper, with navigation, editing,
  and enumeration. See Huet
Базовый синтаксис
• Код – структуры данных
• Выражение – список, первый элемент бывает:
   • Функция
   • Макрос
   • Специальная форма

• Примеры:
  (def a 1)          (defn square [x] (* x x))

  (+ 1 2)            (defmacro when [x & body]
                        `(if ~x (do ~@body)))
Базовые типы данных
• Числа (целые, рациональные, вещественные):
   42, 1/3, 12345678901234567N, 4.2, 42.2M
• Строки:                 "string... "
• Знаки (characters):      a, newline, …
• Регулярные выражения:    #"d+"
• Логические значения:     true, false
• как null в Java          nil
• Симбол (symbol):         name
• keyword:                 :name,
                          (:name {:name "test"})
Коллекции
• Разные коллекции:
   • Списки:             '(1 2 3 "abc") (quoting)
   • Вектора:               [1 2 3]       (no quoting)
   • Отображения (maps): {:k1 1234 :k2 "value"}
   • Множества:             #{:val1 "text" 1 2 10}
• persistent & transient коллекции
• Вектора, отображения и множества сами являются
  функциями:

  ([1 2 3] 2)            ({:a 1 :b 2 :c 3} :b)
  => 3                   => 2
   (no quoting)          (no quoting)
Persistent collections
• Новая копия данных при
  изменении
• Затрагивается только
  измененная часть
• Производительность
  сравнима с коллекциями
  Java


                    Rich Hickey to the Western Mass.
                    Developers Group on Clojure and
                    concurrency.
                    (2,5h – well invested time!)
                    http://blip.tv/clojure/clojure-concurrency-819147
                    http://www.youtube.com/user/ClojureTV
Последовательности
   •   Последовательности (sequences):
   •   Коллекции Clojure & Java, массивы, iterable, …
   •   "Ленивые" операции над последовательностями
   •   Могут быть бесконечными
   •   Один набор операций над последовательностями:
        map, reduce / reductions, filter, …
       http://www.infoq.com/presentations/Clojure-Reducers
Tim McCormack, http://www.brainonfire.net/files/seqs-and-colls/main.html
Google Lectures on MapReduce




                     http://www.youtube.com/watch?v=yjPBkvYh-ss
                     http://www.youtube.com/watch?v=-vD6PUdf3Js
                     http://www.youtube.com/watch?v=5Eib_H_zCEY
                     http://www.youtube.com/watch?v=1ZDybXl212Q
     Aaron Kimball   http://www.youtube.com/watch?v=BT-piFBP4fE
Clojure Destructuring
http://blog.jayfields.com/2010/07/clojure-destructuring.html

(def indexes [1 2 3])
; #'user/indexes

(let [[x & more :as full-list] indexes]
    (println "x:" x "more:" more "full list:"
full-list))
; x: 1 more: (2 3) full list: [1 2 3]


(def point {:x 5 :y 7})
; #'user/point

(let [{the-x :x the-y :y} point]
      (println "x:" the-x "y:" the-y))
; x: 5 y: 7                                                    Jay Fields
Clojure core.logic
                                         Prolog


Dan Friedman
          William Byrd




 https://www.youtube.com/watch?v=A7de6pC-tnU
Clojure core.logic
http://www.vimeo.com/45128721
                                Prolog
IDE & средства сборки кода
• Поддержка в IDE/редакторах:
   – Eclipse (Counterclockwise)
   – Netbeans (Enclojure)
   – IntelliJ IDEA (La Clojure)
   – Emacs + SLIME (depricated) или nRepl / ritz-repl
       • Ubuntu: https://launchpad.net/~cassou/+archive/emacs
       • Windows: ftp://ftp.gnu.org/gnu/emacs/windows/, cygwin.com
   – VimClojure
   – LightTable, Textmate, Sublime Text 2, Jedit
• Средства сборки кода:
   – Поддержка Clojure в Maven, Ant, Cake, Gradle
   – самый популярный: Leiningen (спасибо, Phil)
                                                          Phil Hagelberg
Библиотеки и репозитории
• Простой доступ к библиотекам JVM
• Библиотеки написанные на Clojure:
  – Web-разработка: Compojure, Ring, Scriptjure
  – RDBMS: ClojureQL, clojure.java.jdbc, Korma
  – NoSQL: Monger, Clouch, …
  – GUI: Seesaw
    http://darevay.com/talks/clojurewest2012/#/title-slide
  – Логическое программирование: core.logic
• Репозитории: Maven Central, Clojars.org
Clojure + Leiningen + Emacs 24/emacs-live
on Windows 8
Caveat: emacs-live does not yet collaborate on Windows with ritz-repl,
i.e.emacs-live provides not the full SLIME functionality as per mid Jan. 2013
•   Install Java JDK from http://www.java.com
•   Install cygwin, use defaults; use cygwin package manager to install git
•   Install Leiningen 2.0 in cygwin, this includes Clojure:
     – $ cd; git clone 
       https://raw.github.com/technomancy/leiningen/preview/bin/lein
     – Place it on your $PATH, preferably use ~/bin
     – $ chmod 755 ~/bin/lein
     – $ lein self-install
•   Install Emacs 24 + emacs-live in Windows:
     • Download Emacs 24 from ftp://ftp.gnu.org/gnu/emacs/windows/
     • Download emacs-live from https://github.com/overtone/emacs-live
     • Move directory emacs-live to
        C:Users%your user name%AppDataRoaming.emacs.d
Let´s start: 4clojure.com




              See also:
              http://www.lisperati.com/clojure-spels/casting.html
              https://github.com/relevance/labrepl
              http://clojurekoans.com/
              http://tryclj.com/
Lazy Searching

;;;; 4clojure #108

;; find f satisfying:
;
(= 64 (f (map #(* % % %) (range)) ;; perfect cubes
          (filter #(zero? (bit-and % (dec %))) (range)) ;; powers of 2
          (iterate inc 20))) ;; at least as large as 20

;; caution: the function for powers of 2 becomes
;; highly inefficient for n > 28:
;
(time (last (take 28 (filter #(zero? (bit-and % (dec %))) (range)))))
;"Elapsed time: 25954.456087 msecs"
;67108864
Lazy Searching

;; define predicate on ordered, infinite seqs:
;
(defn in? [coll x]
  (cond (empty? coll) false
        (= x (first coll)) true
        (< x (first coll)) false
        :else (in? (rest coll) x)))

;; for convenience:
;
(def inf-seq-1 (map #(* % % %) (range)))
(def inf-seq-2 (filter #(zero? (bit-and % (dec %))) (range)))
(def inf-seq-3 (iterate inc 20))
Lazy Searching

;; predicate in? can be used on a finite list of infinite seqs:
;
(take 10
  (for [i (range)]
    [i (map #(in? % i) (list inf-seq-1 inf-seq-2 inf-seq-3))]))
;([0 (true true   false)] [1 (true true false)] [2 (false true false)]
[3 (false false   false)] [4 (false true false)] [5 (false false false)]
[6 (false false   false)] [7 (false false false)] [8 (true true false)]
[9 (false false   false)])


(first (drop 64
 (for [i (range)]
   [i (map #(in? % i) (list inf-seq-1 inf-seq-2 inf-seq-3))])))
;[64 (true true true)]
Lazy Searching
;; for convenience:
;
(def three-infinite-seqs (list inf-seq-1 inf-seq-2 inf-seq-3))

;; predicate in? can be reduced on a finite list
;; of infinite seqs;
;; for convenience define in-seqs?:
;
(defn in-seqs? [x & colls]
  (reduce #(and %1 %2) (map #(in? % x) colls)))

(apply in-seqs? 4 three-infinite-seqs)
;false
(apply in-seqs? 64 three-infinite-seqs)
;true
Lazy Searching
;; in-seqs? can be used to build a vector tuple in a for loop:
(take 10
      (for [i (range)]
        [i (apply in-seqs? i three-infinite-seqs)]))
;([0 false] [1 false] [2 false] [3 false] [4 false] [5 false]
[6 false] [7 false] [8 false] [9 false])



;; hence, filtering on the infinite seq of tuples is possible:
;
(first
 (filter #(true? (% 1))
         (for [i (range)]
           [i (apply in-seqs? i three-infinite-seqs)]))
;[64 true]
Lazy Searching

;; finally, pick the solution from the right tupel:
;
((first
 (filter #(true? (% 1))
         (for [i (range)]
           [i (apply in-seqs? i three-infinite-seqs)]))) 0)
;64




;; Remark:
;;
;; optimize the solution by using -> / ->>
;; http://kotka.de/blog/2010/04/Did_you_know_II.html
Balanced Primes – 1st
;;;; 4clojure #116 (Prime Sandwich)

(= 1103 (nth (filter balanced? (range)) 15))

(defn prime? [n]
  (cond (< n 2) false
        (= n 2) true
        :else (= '(1)
          (filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n)))))))

(defn p-before [p] (last (filter prime? (range p))))

(defn p-after [p] (first (filter prime? (drop (inc p) (range)))))

(defn balanced? [p]
  (cond (< p 4) false
        (prime? p) (= p (/ (+ (p-before p) (p-after p)) 2))
        :else false))
Balanced Primes – 2nd

(= 1103 (nth (filter balanced? (range)) 15))

;; prime?, balanced? as before
;; balanced? needs to be refreshed
;; and (take 10 primes)
;;
(def primes (filter prime? (range)))

(defn p-before [p] (last (filter #(< % p) primes)))

(defn p-after [p] (first (filter #(> % p) primes)))
Balanced Primes – 3rd
(= 1103 (nth (filter balanced? (range)) 15))

;; prime?, primes, in? as before

(def partitioned-primes
    (map #(vector (second %)
    (= (second %) (/ (+ (first %) (last %)) 2)))
    (partition 3 1 primes)))

(def balanced-primes
    (map #(% 0) (filter #(true? (% 1)) partitioned-primes)))

(defn balanced? [p]
    (in? balanced-primes p)))
Вопросы?


Спасибо за внимание.

Contenu connexe

Tendances

ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]Guillermo Paz
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Charles Nutter
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Alfresco the clojure way -- Slides from the Alfresco DevCon2011Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Alfresco the clojure way -- Slides from the Alfresco DevCon2011Carlo Sciolla
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 
Practical REPL-driven Development with Clojure
Practical REPL-driven Development with ClojurePractical REPL-driven Development with Clojure
Practical REPL-driven Development with ClojureKent Ohashi
 
GraphQL API in Clojure
GraphQL API in ClojureGraphQL API in Clojure
GraphQL API in ClojureKent Ohashi
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracerrahulrevo
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015Charles Nutter
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Webnickmbailey
 
Doctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPDoctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPGuilherme Blanco
 

Tendances (20)

ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013
 
node ffi
node ffinode ffi
node ffi
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Alfresco the clojure way -- Slides from the Alfresco DevCon2011Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
Practical REPL-driven Development with Clojure
Practical REPL-driven Development with ClojurePractical REPL-driven Development with Clojure
Practical REPL-driven Development with Clojure
 
Dispatch in Clojure
Dispatch in ClojureDispatch in Clojure
Dispatch in Clojure
 
GraphQL API in Clojure
GraphQL API in ClojureGraphQL API in Clojure
GraphQL API in Clojure
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
ORMs in Golang
ORMs in GolangORMs in Golang
ORMs in Golang
 
Java 8 briefing
Java 8 briefingJava 8 briefing
Java 8 briefing
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Web
 
Doctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPDoctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHP
 

Similaire à iSoligorsk #3 2013

[NDC2017] 딥러닝으로 게임 콘텐츠 제작하기 - VAE를 이용한 콘텐츠 생성 기법 연구 사례
[NDC2017] 딥러닝으로 게임 콘텐츠 제작하기 - VAE를 이용한 콘텐츠 생성 기법 연구 사례[NDC2017] 딥러닝으로 게임 콘텐츠 제작하기 - VAE를 이용한 콘텐츠 생성 기법 연구 사례
[NDC2017] 딥러닝으로 게임 콘텐츠 제작하기 - VAE를 이용한 콘텐츠 생성 기법 연구 사례Hwanhee Kim
 
Rapid prototyping with solr - By Erik Hatcher
Rapid prototyping with solr -  By Erik Hatcher Rapid prototyping with solr -  By Erik Hatcher
Rapid prototyping with solr - By Erik Hatcher lucenerevolution
 
State of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeState of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeKonrad Malawski
 
XML Amsterdam 2012 Keynote
XML Amsterdam 2012 KeynoteXML Amsterdam 2012 Keynote
XML Amsterdam 2012 Keynotejimfuller2009
 
A Quick Introduction to Programmable Logic
A Quick Introduction to Programmable LogicA Quick Introduction to Programmable Logic
A Quick Introduction to Programmable LogicOmer Kilic
 
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeEuroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeMetosin Oy
 
"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - Chicago"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - ChicagoErik Hatcher
 
Regex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadRegex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadAll Things Open
 
Real-time Semantic Web with Twitter Annotations
Real-time Semantic Web with Twitter AnnotationsReal-time Semantic Web with Twitter Annotations
Real-time Semantic Web with Twitter AnnotationsJoshua Shinavier
 
EclipseOMRBuildingBlocks4Polyglot_TURBO18
EclipseOMRBuildingBlocks4Polyglot_TURBO18EclipseOMRBuildingBlocks4Polyglot_TURBO18
EclipseOMRBuildingBlocks4Polyglot_TURBO18Xiaoli Liang
 
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem novaKotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem novaVíctor Leonel Orozco López
 
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...PROIDEA
 
Data Science with Solr and Spark
Data Science with Solr and SparkData Science with Solr and Spark
Data Science with Solr and SparkLucidworks
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Martijn Verburg
 
SXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBustersSXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBustersElena-Oana Tabaranu
 
Clojure/conj 2017
Clojure/conj 2017Clojure/conj 2017
Clojure/conj 2017Darren Kim
 
OWASP Poland Day 2018 - Andrzej Dyjak - Zero Trust Theorem
OWASP Poland Day 2018 - Andrzej Dyjak - Zero Trust TheoremOWASP Poland Day 2018 - Andrzej Dyjak - Zero Trust Theorem
OWASP Poland Day 2018 - Andrzej Dyjak - Zero Trust TheoremOWASP
 

Similaire à iSoligorsk #3 2013 (20)

[NDC2017] 딥러닝으로 게임 콘텐츠 제작하기 - VAE를 이용한 콘텐츠 생성 기법 연구 사례
[NDC2017] 딥러닝으로 게임 콘텐츠 제작하기 - VAE를 이용한 콘텐츠 생성 기법 연구 사례[NDC2017] 딥러닝으로 게임 콘텐츠 제작하기 - VAE를 이용한 콘텐츠 생성 기법 연구 사례
[NDC2017] 딥러닝으로 게임 콘텐츠 제작하기 - VAE를 이용한 콘텐츠 생성 기법 연구 사례
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
 
Rapid prototyping with solr - By Erik Hatcher
Rapid prototyping with solr -  By Erik Hatcher Rapid prototyping with solr -  By Erik Hatcher
Rapid prototyping with solr - By Erik Hatcher
 
State of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeState of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to come
 
XML Amsterdam 2012 Keynote
XML Amsterdam 2012 KeynoteXML Amsterdam 2012 Keynote
XML Amsterdam 2012 Keynote
 
A Quick Introduction to Programmable Logic
A Quick Introduction to Programmable LogicA Quick Introduction to Programmable Logic
A Quick Introduction to Programmable Logic
 
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeEuroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
 
"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - Chicago"Solr Update" at code4lib '13 - Chicago
"Solr Update" at code4lib '13 - Chicago
 
Regex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadRegex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language Instead
 
Real-time Semantic Web with Twitter Annotations
Real-time Semantic Web with Twitter AnnotationsReal-time Semantic Web with Twitter Annotations
Real-time Semantic Web with Twitter Annotations
 
EclipseOMRBuildingBlocks4Polyglot_TURBO18
EclipseOMRBuildingBlocks4Polyglot_TURBO18EclipseOMRBuildingBlocks4Polyglot_TURBO18
EclipseOMRBuildingBlocks4Polyglot_TURBO18
 
Clojure presentation
Clojure presentationClojure presentation
Clojure presentation
 
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem novaKotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
 
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
 
Data Science with Solr and Spark
Data Science with Solr and SparkData Science with Solr and Spark
Data Science with Solr and Spark
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)
 
SXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBustersSXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBusters
 
Clojure/conj 2017
Clojure/conj 2017Clojure/conj 2017
Clojure/conj 2017
 
OWASP Poland Day 2018 - Andrzej Dyjak - Zero Trust Theorem
OWASP Poland Day 2018 - Andrzej Dyjak - Zero Trust TheoremOWASP Poland Day 2018 - Andrzej Dyjak - Zero Trust Theorem
OWASP Poland Day 2018 - Andrzej Dyjak - Zero Trust Theorem
 
C Sharp Crash Course
C Sharp Crash CourseC Sharp Crash Course
C Sharp Crash Course
 

Dernier

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 

Dernier (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 

iSoligorsk #3 2013

  • 1. Introduction to Clojure Soligorsk, 26.01.2013 Friedrich Boeckh
  • 2. Clojure rocks & Sam Aaron is badass Overtone, http://blip.tv/clojure/sam-aaron-programming-music-with-overtone-5970273
  • 3. ThoughtWorks 2012: Clojure is on the Radar http://www.thoughtworks.com/articles /technology-radar-october-2012 … even Microsoft cares … as always - it does not make everybody happy: http://cafe.elharo.com/programming/java- programming/why-functional-programming-in-java-is- dangerous/
  • 4. World singles Sean Corfield http://corfield.org/articles/WorldSinglesWeb.pdf • 3,000,000 members • 1,000,000 emails / day • 80,000 logins / day • 2,000 concurrent users (average)
  • 6. Clojure at a bank Malcolm Sparks http://blog.malcolmsparks.com/?p=17
  • 7. Clojure at another bank Jon Pither http://www.pitheringabout.com/?p=693
  • 8. Clojure at yet another bank
  • 9. Clojure at Nokia Entertainment http://skillsmatter.com/event/clojure/clojure-at-nokia-entertainment
  • 10. Big Data Done Better – Mastodon C https://www.mastodonc.com/
  • 11. Clojure gives Innovation a Boost Stuart Halloway Justin Gethland & Rich Hickey
  • 12. Russian wording in the following from Alex Ott´s talk at itsea 2012 http://de.slideshare.net/alexott/clojure-lisp-for-the-modern-world http://alexott.net/ru/clojure/clojure-intro/index.html http://alexott.net/en/clojure/video.html
  • 13. Что такое Clojure? • Rich Hickey, 17.10.2007, с v1.4, RC v1.5 • Lisp-ообразный • Функциональный • Конкурентное программирование http://stackoverflow.com/questions/1050222/concurrency-vs- parallelism-what-is-the-difference • Многоплатформенный (JVM, .Net, JavaScript, etc.) • Открытый исходный код и либеральная лицензия Eclipse Public License 1.0 • Активное сообщество разработчиков • Коммерческое применение • Коммерческая поддержка
  • 14. Активное сообщество разработчиков Sean Corfield http://corfield.org/articles/WorldSinglesWeb.pdf, mid 2012
  • 15. Почему Lisp? • Простой синтаксис - code as data structures homoiconic • Метапрограммирование (макросы) • Создание доменно-специфических языков DSLs • Генерация кода во время компиляции • Возможность избежать повторений • Генерация и выполнение кода в runtime • Интерактивная разработка REPL • Динамически типизированный
  • 16. Lisp? 7 элементов + fn нотация John McCarthy 1927 - 2011 Lisp Specification, 1958
  • 17. Lisp? 7 элементов + fn нотация Paul Graham, The Roots of Lisp http://www.paulgraham.com/rootsoflisp.html http://www.cse.sc.edu/~mgv/csce531sp07/jmc.pdf • (quote x) returns x • (atom x)returns the atom t (true) if the value of x is an atom or the empty list. Otherwise it returns (). • (eq x y) returns t if the values of x and y are the same atom or both the empty list, and () otherwise. • (car x) expects the value of x to be a list, and returns its first element. • (cdr x) expects the value of x to be a list, and returns everything after the first element. • (cons x y) expects the value of y to be a list, and returns a list containing the value of x followed by the elements of the value of y. • (cond (p1 e1) ... (pn en)) is evaluated as follows. The p expressions are evaluated in order until one returns t (true). When one is found, the value of the corresponding e expression is returned as the value of the whole cond expression. • A function is expressed as (lambda (p1 ... pn) e), where p1 ... pn are atoms, called parameters, and e is an expression.
  • 18. Богатство Lisp наследия • Hal Abelson, Jerry Sussman and Julie Sussman, Structure and Interpretation of Computer Programs (SICP), http://mitpress.mit.edu/sicp/, http://newstar.rinet.ru/~goga/sicp/sicp.pdf (russ.), http://ocw.mit.edu/courses/electrical-engineering-and- computer-science/6-001-structure-and-interpretation-of- computer-programs-spring-2005/video-lectures/ • Peter Seibel, Practical Common Lisp, http://www.gigamonkeys.com/book/ • Paul Graham, On Lisp, http://www.paulgraham.com/onlisp.html, http://lib.store.yahoo.net/lib/paulgraham/onlisp.pdf
  • 19. Богатство Lisp наследия Conrad Barski (M.D.) http://vimeo.com/9605639
  • 20. Богатство Lisp наследия • VLSI design, Boeing, US government & military, ITA Software (in 2010 acquired by Google) • NASA, The Remote Agent Experiment - Debugging code from 60 million miles away, Ron Garret, 14 February 2012 • Paul Graham, Beating the Averages, http://www.paulgraham.com/avg.html, http://lib.store.yahoo.net/lib/paulgraham/bbnexcerpts.txt • Andreas Lehmann, Common Lisp Raytracer, (source code transcript e. g. here https://github.com/fbmnds/clrt), videos and PDFs http://rudairandamacha.blogspot.de/2012/09/writing-simple- raytracer-in-common-lisp.html
  • 21. Богатство Lisp наследия • Peter Norvig, Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp (PAIP), http://norvig.com/paip.html • Daniel P. Friedman, Matthias Felleisen, The Little Schemer, http://mitpress.mit.edu/books/little-schemer • Overview by Vsevolod Dyomkin, http://lisp-univ-etc.blogspot.com/2012/12/lisp-books.html • Rich Hickey, Books that influenced Clojure, http://www.amazon.com/gp/richpub/listmania/fullview/R3LG3Z BZS4GCTH
  • 22. Богатство Lisp наследия – Emacs ?? Marco Baringer's SLIME Tutorial Video: http://www.youtube.com/watch?v=_B_4vhsmRRI ( underscore)
  • 23. Отличия от других Lisp’ов • Немного упрощенный синтаксис -- меньше скобочек • Неизменяемые данные (immutability) • Добавлено больше базовых структур данных: вектора, отображения (maps) и т.д. • Расширяемый reader, но без reader macros • "Ленивые" коллекции (lazy-seq) • Мета-информация привязанная к данным и функциям • Case-sensitive names • Исключения вместо условий/рестартов • Полиморфизм: протоколы и мультиметоды • Software Transactional Memory System (STM) • Java Interoperation, http://clojure.org/java_interop ( underscore)
  • 24. Полиморфизм на Clojure • Протоколы, мультиметоды … Stuart Sierra, https://www.ibm.com/developerworks/java/library/j-clojure-protocols/
  • 25. Полиморфизм на Clojure • Протоколы, мультиметоды http://oredev.org/2012/sessions/expressing-yourself-polymorphism-in-clojure
  • 26. Software Transactional Memory System (STM) Graig Andera http://pluralsight.com/training/Courses/TableOfContents/clojure-concurrency-tutorial
  • 27. Почему ФП? • Функции в математическом смысле Lambda Calculus • Функции – объекты первого порядка first-class objects, higher-order functions (HOF) • Неизменяемость данных immutability • Отсутствие побочных эффектов • Возможность автоматической параллелизации кода • Меньше проблем с конкурентным выполнением кода
  • 28. Lambda Calculus ~ “effectively programmable” Alonzo Church Stephen Kleene Alan Turing 1903 - 1995 1909 - 1994 1912 - 1954
  • 29. Lambda Calculus http://www.infoq.com/presentations/Y-Combinator (defn Y [h] Jim Weirich (Y-rich) ((fn [f] (f f)) (fn [f] (h (fn [n] ((f f) n)))))) (def fact (Y (fn [g] (fn [n] (if (< n 2) 1 (* n (g (dec n)))))))) transcript by Michael Kohl, http://citizen428.net/blog/2010/12/14/clojure-deriving-the-y-combinator-in-7-stolen-steps/
  • 30. Почему ФП? 1922 - 1990 You want functions?
  • 32. Clojure / ФП - Namespaces http://clojure.org/namespaces • Namespaces are mappings from simple (unqualified) symbols to Vars and/or Classes. • Namespaces are first-class, they can be enumerated etc. • Namespaces are also dynamic, they can be created, removed and modified at runtime, at the Repl etc. • The best way to set up a new namespace at the top of a Clojure source file is to use the ns macro. • The current namespace, *ns* can and should be set only with a call to in-ns or the ns macro, both of which create the namespace if it doesn't exist.
  • 33. Clojure / ФП - Namespaces • clojure.core - Fundamental library of the Clojure language • clojure.data - Non-core data functions. • clojure.inspector - Graphical object inspector for Clojure data structures. • clojure.java.browse - Start a web browser from Clojure • clojure.java.io • clojure.java.javadoc - A repl helper to quickly open javadocs. • clojure.java.shell • clojure.main • clojure.pprint - A Pretty Printer for Clojure • clojure.reflect - Reflection on Host Types • clojure.repl - Utilities meant to be used interactively at the REPL
  • 34. Clojure / ФП - Namespaces • clojure.set • clojure.stacktrace - Print stack traces oriented towards Clojure, not Java. • clojure.string • clojure.template - Macros that expand to repeated copies of a template expression. • clojure.test - A unit testing framework. • clojure.walk • clojure.xml - XML reading/writing. • clojure.zip - Functional hierarchical zipper, with navigation, editing, and enumeration. See Huet
  • 35. Базовый синтаксис • Код – структуры данных • Выражение – список, первый элемент бывает: • Функция • Макрос • Специальная форма • Примеры: (def a 1) (defn square [x] (* x x)) (+ 1 2) (defmacro when [x & body] `(if ~x (do ~@body)))
  • 36. Базовые типы данных • Числа (целые, рациональные, вещественные): 42, 1/3, 12345678901234567N, 4.2, 42.2M • Строки: "string... " • Знаки (characters): a, newline, … • Регулярные выражения: #"d+" • Логические значения: true, false • как null в Java nil • Симбол (symbol): name • keyword: :name, (:name {:name "test"})
  • 37. Коллекции • Разные коллекции: • Списки: '(1 2 3 "abc") (quoting) • Вектора: [1 2 3] (no quoting) • Отображения (maps): {:k1 1234 :k2 "value"} • Множества: #{:val1 "text" 1 2 10} • persistent & transient коллекции • Вектора, отображения и множества сами являются функциями: ([1 2 3] 2) ({:a 1 :b 2 :c 3} :b) => 3 => 2 (no quoting) (no quoting)
  • 38. Persistent collections • Новая копия данных при изменении • Затрагивается только измененная часть • Производительность сравнима с коллекциями Java Rich Hickey to the Western Mass. Developers Group on Clojure and concurrency. (2,5h – well invested time!) http://blip.tv/clojure/clojure-concurrency-819147 http://www.youtube.com/user/ClojureTV
  • 39. Последовательности • Последовательности (sequences): • Коллекции Clojure & Java, массивы, iterable, … • "Ленивые" операции над последовательностями • Могут быть бесконечными • Один набор операций над последовательностями: map, reduce / reductions, filter, … http://www.infoq.com/presentations/Clojure-Reducers Tim McCormack, http://www.brainonfire.net/files/seqs-and-colls/main.html
  • 40. Google Lectures on MapReduce http://www.youtube.com/watch?v=yjPBkvYh-ss http://www.youtube.com/watch?v=-vD6PUdf3Js http://www.youtube.com/watch?v=5Eib_H_zCEY http://www.youtube.com/watch?v=1ZDybXl212Q Aaron Kimball http://www.youtube.com/watch?v=BT-piFBP4fE
  • 41. Clojure Destructuring http://blog.jayfields.com/2010/07/clojure-destructuring.html (def indexes [1 2 3]) ; #'user/indexes (let [[x & more :as full-list] indexes] (println "x:" x "more:" more "full list:" full-list)) ; x: 1 more: (2 3) full list: [1 2 3] (def point {:x 5 :y 7}) ; #'user/point (let [{the-x :x the-y :y} point] (println "x:" the-x "y:" the-y)) ; x: 5 y: 7 Jay Fields
  • 42. Clojure core.logic Prolog Dan Friedman William Byrd https://www.youtube.com/watch?v=A7de6pC-tnU
  • 44. IDE & средства сборки кода • Поддержка в IDE/редакторах: – Eclipse (Counterclockwise) – Netbeans (Enclojure) – IntelliJ IDEA (La Clojure) – Emacs + SLIME (depricated) или nRepl / ritz-repl • Ubuntu: https://launchpad.net/~cassou/+archive/emacs • Windows: ftp://ftp.gnu.org/gnu/emacs/windows/, cygwin.com – VimClojure – LightTable, Textmate, Sublime Text 2, Jedit • Средства сборки кода: – Поддержка Clojure в Maven, Ant, Cake, Gradle – самый популярный: Leiningen (спасибо, Phil) Phil Hagelberg
  • 45. Библиотеки и репозитории • Простой доступ к библиотекам JVM • Библиотеки написанные на Clojure: – Web-разработка: Compojure, Ring, Scriptjure – RDBMS: ClojureQL, clojure.java.jdbc, Korma – NoSQL: Monger, Clouch, … – GUI: Seesaw http://darevay.com/talks/clojurewest2012/#/title-slide – Логическое программирование: core.logic • Репозитории: Maven Central, Clojars.org
  • 46. Clojure + Leiningen + Emacs 24/emacs-live on Windows 8 Caveat: emacs-live does not yet collaborate on Windows with ritz-repl, i.e.emacs-live provides not the full SLIME functionality as per mid Jan. 2013 • Install Java JDK from http://www.java.com • Install cygwin, use defaults; use cygwin package manager to install git • Install Leiningen 2.0 in cygwin, this includes Clojure: – $ cd; git clone https://raw.github.com/technomancy/leiningen/preview/bin/lein – Place it on your $PATH, preferably use ~/bin – $ chmod 755 ~/bin/lein – $ lein self-install • Install Emacs 24 + emacs-live in Windows: • Download Emacs 24 from ftp://ftp.gnu.org/gnu/emacs/windows/ • Download emacs-live from https://github.com/overtone/emacs-live • Move directory emacs-live to C:Users%your user name%AppDataRoaming.emacs.d
  • 47. Let´s start: 4clojure.com See also: http://www.lisperati.com/clojure-spels/casting.html https://github.com/relevance/labrepl http://clojurekoans.com/ http://tryclj.com/
  • 48. Lazy Searching ;;;; 4clojure #108 ;; find f satisfying: ; (= 64 (f (map #(* % % %) (range)) ;; perfect cubes (filter #(zero? (bit-and % (dec %))) (range)) ;; powers of 2 (iterate inc 20))) ;; at least as large as 20 ;; caution: the function for powers of 2 becomes ;; highly inefficient for n > 28: ; (time (last (take 28 (filter #(zero? (bit-and % (dec %))) (range))))) ;"Elapsed time: 25954.456087 msecs" ;67108864
  • 49. Lazy Searching ;; define predicate on ordered, infinite seqs: ; (defn in? [coll x] (cond (empty? coll) false (= x (first coll)) true (< x (first coll)) false :else (in? (rest coll) x))) ;; for convenience: ; (def inf-seq-1 (map #(* % % %) (range))) (def inf-seq-2 (filter #(zero? (bit-and % (dec %))) (range))) (def inf-seq-3 (iterate inc 20))
  • 50. Lazy Searching ;; predicate in? can be used on a finite list of infinite seqs: ; (take 10 (for [i (range)] [i (map #(in? % i) (list inf-seq-1 inf-seq-2 inf-seq-3))])) ;([0 (true true false)] [1 (true true false)] [2 (false true false)] [3 (false false false)] [4 (false true false)] [5 (false false false)] [6 (false false false)] [7 (false false false)] [8 (true true false)] [9 (false false false)]) (first (drop 64 (for [i (range)] [i (map #(in? % i) (list inf-seq-1 inf-seq-2 inf-seq-3))]))) ;[64 (true true true)]
  • 51. Lazy Searching ;; for convenience: ; (def three-infinite-seqs (list inf-seq-1 inf-seq-2 inf-seq-3)) ;; predicate in? can be reduced on a finite list ;; of infinite seqs; ;; for convenience define in-seqs?: ; (defn in-seqs? [x & colls] (reduce #(and %1 %2) (map #(in? % x) colls))) (apply in-seqs? 4 three-infinite-seqs) ;false (apply in-seqs? 64 three-infinite-seqs) ;true
  • 52. Lazy Searching ;; in-seqs? can be used to build a vector tuple in a for loop: (take 10 (for [i (range)] [i (apply in-seqs? i three-infinite-seqs)])) ;([0 false] [1 false] [2 false] [3 false] [4 false] [5 false] [6 false] [7 false] [8 false] [9 false]) ;; hence, filtering on the infinite seq of tuples is possible: ; (first (filter #(true? (% 1)) (for [i (range)] [i (apply in-seqs? i three-infinite-seqs)])) ;[64 true]
  • 53. Lazy Searching ;; finally, pick the solution from the right tupel: ; ((first (filter #(true? (% 1)) (for [i (range)] [i (apply in-seqs? i three-infinite-seqs)]))) 0) ;64 ;; Remark: ;; ;; optimize the solution by using -> / ->> ;; http://kotka.de/blog/2010/04/Did_you_know_II.html
  • 54. Balanced Primes – 1st ;;;; 4clojure #116 (Prime Sandwich) (= 1103 (nth (filter balanced? (range)) 15)) (defn prime? [n] (cond (< n 2) false (= n 2) true :else (= '(1) (filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n))))))) (defn p-before [p] (last (filter prime? (range p)))) (defn p-after [p] (first (filter prime? (drop (inc p) (range))))) (defn balanced? [p] (cond (< p 4) false (prime? p) (= p (/ (+ (p-before p) (p-after p)) 2)) :else false))
  • 55. Balanced Primes – 2nd (= 1103 (nth (filter balanced? (range)) 15)) ;; prime?, balanced? as before ;; balanced? needs to be refreshed ;; and (take 10 primes) ;; (def primes (filter prime? (range))) (defn p-before [p] (last (filter #(< % p) primes))) (defn p-after [p] (first (filter #(> % p) primes)))
  • 56. Balanced Primes – 3rd (= 1103 (nth (filter balanced? (range)) 15)) ;; prime?, primes, in? as before (def partitioned-primes (map #(vector (second %) (= (second %) (/ (+ (first %) (last %)) 2))) (partition 3 1 primes))) (def balanced-primes (map #(% 0) (filter #(true? (% 1)) partitioned-primes))) (defn balanced? [p] (in? balanced-primes p)))