SlideShare una empresa de Scribd logo
1 de 78
Descargar para leer sin conexión
Episode VI:
                             Clojure
                           Завръщането на Джедаите




Saturday, November 3, 12
Saturday, November 3, 12
bozhidar

                           user> (:twitter bozhidar)
                           "@bbatsov"
                           user> (bozhidar :blog)
                           "http://batsov.com"
                           user> (:github bozhidar)
                           "http://github.com/bbatsov"



Saturday, November 3, 12
http://tradeo.com
Saturday, November 3, 12
Saturday, November 3, 12
@emacs_knight
Saturday, November 3, 12
Мечки
Saturday, November 3, 12
Мечка
Saturday, November 3, 12
Мечка и Компютър
Saturday, November 3, 12
Защо съм тук?



Saturday, November 3, 12
Програмистите са идиоти!
Saturday, November 3, 12
Затънали сме до уши в
                     калта наречена
                “инцидентна сложност”
                 и въобще не си даваме
                     сметка за това...

Saturday, November 3, 12
public boolean hasUpperCase(String word) {
                               if (word == null) {
                                   return false;
                               }
                               int len = word.length();
                               for (int i = 0; i < len; i++) {
                                   if (Character.isUpperCase(word.charAt(i))) {
                                       return true;
                                   }
                               }
                               return false;
                           }




         (defn has-uppercase? [string]
           (some #(Character/isUpperCase %) string))



Saturday, November 3, 12
Новото е добре
                           забравено старо.


Saturday, November 3, 12
Конвенционален език за
                               програмиране
Saturday, November 3, 12
Читав език за програмиране
Saturday, November 3, 12
Функционален език за
                              програмиране
Saturday, November 3, 12
Common Lisp
Saturday, November 3, 12
Clojure
Saturday, November 3, 12
Lisp




Saturday, November 3, 12
Saturday, November 3, 12
Магията на Lisp
                    • Половин вековна история
                    • Често имитиран, вечно ненадминат
                    • Изключително малко ядро
                    • Почти никакъв синтаксис
                    • “Кодът е данни” (code is data)
                    • Интерактивно програмиране
Saturday, November 3, 12
Проблемите на Lisp
                   (Common Lisp/Scheme)
                    • Никаква иновация след
                           стандартизирането им
                    • Сегментация
                    • Думата “едновременно” (concurrently) не
                           се споменава в спецификациите им
                    • Повечето Lisp-ове дефинират сами
                           своята платформа


Saturday, November 3, 12
Истинските мъже не ги е страх от
                           малко скоби!
Saturday, November 3, 12
Хората имат
                           неприятния навик да
                              бъркат думите
                               “познато” и
                              “интуитивно”.

Saturday, November 3, 12
"We were after the C++ programmers.
                  We managed to drag a lot of them about
                            halfway to Lisp."
Saturday, November 3, 12
Ruby was a Lisp originally, in theory.




                 “Ruby was a Lisp originally, in theory.”

Saturday, November 3, 12
Голяма част от
                   езиците, които стават
                   за нещо са повлияни
                   пряко или косвено от
                          Lisp!!!

Saturday, November 3, 12
ФАКТ!



Saturday, November 3, 12
A language that doesn’t affect the way you
                        think about programming is not worth
                                      knowing.

Saturday, November 3, 12
Clojure
Saturday, November 3, 12
Есенцията
                    • Динамичен език за програмиране
                    • JVM/CLR/JavaScript
                    • Модерен диалеакт на Lisp (1)
                    • Функционален по практичен начин
                    • Оптимизиран за паралелно програмиране
                    • Борец за един по-прост свят
Saturday, November 3, 12
Еволюцията на Lisp
                    • сбогом car & cdr (hello first & rest)
                    • по-малко скоби
                    • повече структури от данни с literal
                           синтаксис (set, map, vector)
                    • коварно бърз runtime
                    • стандартизиран runtime
                    • непроменими (immutable) структури данни
Saturday, November 3, 12
(hello clojure)

                    (defn hello-world []
                      (println "Hello, world!"))

                    (defn hello [name]
                      (println
                       (format "Hello, %s!" name)))




Saturday, November 3, 12
user> (hello-world)
                           Hello, world!
                           nil
                           user> (hello "Bozhidar")
                           Hello, Bozhidar!
                           nil



Saturday, November 3, 12
Lisp programmers know the value of
                 everything, but the cost of nothing.
Saturday, November 3, 12
Структури от данни

                    • свързан списък (list)
                    • множество (set)
                    • вектор
                    • асоциативен масив (map/dictionary)
                    • всичко Джавешко и родно

Saturday, November 3, 12
Списък
Saturday, November 3, 12
user> (list 1 2 3)
              (1 2 3)
              user> '(1 2 3)
              (1 2 3)
              user> (def names '("Bozhidar" "Snezhi" "Batman" "Yoda" "Mike"))
              #'user/names
              user> (first names)
              "Bozhidar"
              user> (rest names)
              ("Snezhi" "Batman" "Yoda" "Mike")
              user> (last names)
              "Mike"
              user> (count names)
              5
              user> (map lower-case names)
              ("bozhidar" "snezhi" "batman" "yoda" "mike")
              user> (map count names)
              (8 6 6 4 4)
              user> (apply + (map count names))
              28
              user> (cons "Pesho" names)
              ("Pesho" "Bozhidar" "Snezhi" "Batman" "Yoda" "Mike")
              user> names
              ("Bozhidar" "Snezhi" "Batman" "Yoda" "Mike")
              user> (conj names "Pesho")
              ("Pesho" "Bozhidar" "Snezhi" "Batman" "Yoda" "Mike")
Saturday, November 3, 12
Mutable state is the new spaghetti
                                   code.
Saturday, November 3, 12
user> (filter even? (range 1 10))
  (2 4 6 8)
  user> (every? even? (range 1 10))
  false
  user> (every? even? (filter even? (range 1 10)))
  true
  user> (map #(+ % 5) (range 1 10))
  (6 7 8 9 10 11 12 13 14)
  user> (map (partial + 5) (range 1 10))
  (6 7 8 9 10 11 12 13 14)
  user> (map (comp (partial * 2) (partial + 5))
  (range 1 10))
  (12 14 16 18 20 22 24 26 28)


Saturday, November 3, 12
user> (doc and)
-------------------------
clojure.core/and
([] [x] [x & next])
Macro
  Evaluates exprs one at a time, from left to right. If a form
  returns logical false (nil or false), and returns that value and
  doesn't evaluate any of the other expressions, otherwise it returns
  the value of the last expr. (and) returns true.
nil
user> (source and)
(defmacro and
  "Evaluates exprs one at a time, from left to right. If a form
  returns logical false (nil or false), and returns that value and
  doesn't evaluate any of the other expressions, otherwise it returns
  the value of the last expr. (and) returns true."
  {:added "1.0"}
  ([] true)
  ([x] x)
  ([x & next]
    `(let [and# ~x]
       (if and# (and ~@next) and#))))
nil


Saturday, November 3, 12
Множество
                             (Set)


Saturday, November 3, 12
user> (set '(1 1 2 2 3 3))
                 #{1 2 3}
                 user> (def a-set #{1 2 3 4 5})
                 #'user/a-set
                 user> (contains? a-set 3)
                 true
                 user> (contains? a-set 9)
                 false
                 user> (conj a-set 5)
                 #{1 2 3 4 5}
                 user> (conj a-set 6)
                 #{1 2 3 4 5 6}
                 user> (use 'clojure.set)
                 nil
                 user> (intersection #{1 2 3} #{2 3 4})
                 #{2 3}
                 user> (difference #{1 2 3} #{2 3 4})
                 #{1}
                 user> (union #{1 2 3} #{2 3 4})
                 #{1 2 3 4}
Saturday, November 3, 12
Асоциативен масив
                                 (Map)


Saturday, November 3, 12
user> (hash-map 1 2 3 4)
    {1 2, 3 4}
    user> (hash-map "Batman" "Bruce Wayne" "Superman" "Clark Kent")
    {"Batman" "Bruce Wayne", "Superman" "Clark Kent"}
    user> {:batman "Bruce Wayne", :superman "Clark Kent"}
    {:superman "Clark Kent", :batman "Bruce Wayne"}
    user> (def a-map {:batman "Bruce Wayne", :superman "Clark Kent"})
    #'user/a-map
    user> (:superman a-map)
    "Clark Kent"
    user> (a-map :batman)
    "Bruce Wayne"
    user> (a-map :zorro)
    nil
    user> (merge a-map {:zorro "Diego de la Vega"})
    {:superman "Clark Kent", :batman "Bruce Wayne", :zorro "Diego de la Vega"}
    user> a-map
    {:superman "Clark Kent", :batman "Bruce Wayne"}
    user> (contains? a-map :batman)
    true
    user> (assoc a-map :catwoman "Selina Kyle")
    {:superman "Clark Kent", :batman "Bruce Wayne", :catwoman "Selina Kyle"}
    user> a-map
    {:superman "Clark Kent", :batman "Bruce Wayne"}
    user> (dissoc a-map :batman)
    {:superman "Clark Kent"}
    user> a-map
    {:superman "Clark Kent", :batman "Bruce Wayne"}

Saturday, November 3, 12
Вектор
                           (Vector)


Saturday, November 3, 12
user> (vector 1 2 3 4)
                           [1 2 3 4]
                           user> (into [] '(1 2 3 4))
                           [1 2 3 4]
                           user> (def v (into [] (range 1 5)))
                           #'user/v
                           user> (count v)
                           4
                           user> (nth v 0)
                           1
                           user> (conj v 5)
                           [1 2 3 4 5]
                           user> (pop v)
                           [1 2 3]
                           user> (peek v)
                           4
                           user> [1 2 3 4]
                           [1 2 3 4]


Saturday, November 3, 12
Seq API



Saturday, November 3, 12
Идентичност и
                             състояние


Saturday, November 3, 12
Паралелно
                           програмиране




Saturday, November 3, 12
Законът на Мур даде
                        фира в последните
                             години


Saturday, November 3, 12
Процесорите днес са
                    масово многоядрени.


Saturday, November 3, 12
Програмистите днес
                   пишат масово single-
                threaded(process) софтуер!



Saturday, November 3, 12
Защо така бе, юнаци?
Saturday, November 3, 12
Програмистите са идиоти!
Saturday, November 3, 12
Сложно паралелното
                             програмиране е!
Saturday, November 3, 12
Първи стъпки



Saturday, November 3, 12
user> (def f (future (Thread/sleep 10000) (println "done") 100))
    #'user/f
    user> f
    #<core$future_call$reify__5684@201075c5: :pending>
    user> @f
    done

    100
    user> @f
    100
    user> (def my-delay (delay (println "did some work") 100))
    #'user/my-delay
    user> @my-delay
    did some work
    100
    user> @my-delay
    100



Saturday, November 3, 12
Паралелни операции
                        върху колекции


Saturday, November 3, 12
user> (defn slow-op [n] (Thread/sleep 5000) n)
    #'user/slow-op
    user> (map slow-op (range 1 5))
    (1 2 3 4)
    user> (time (doall (map slow-op (range 1 5))))
    "Elapsed time: 20004.081 msecs"
    (1 2 3 4)
    user> (time (doall (pmap slow-op (range 1 5))))
    "Elapsed time: 5002.705 msecs"
    (1 2 3 4)




Saturday, November 3, 12
Refs



Saturday, November 3, 12
(def picked-numbers (ref #{}))

   (def secret-num (.nextInt (java.util.Random.) 10))

   (defn guess-number [n]
     (print "Enter a guess between 1 and 10: ")
     (flush)
     (let [guess (java.lang.Integer/parseInt (read-line)) ]
       (cond
        (= guess n) (println "You guessed correctly")
        (contains? (deref picked-numbers) n) (println "Pick
   another number!")
        :else (dosync
               (alter picked-numbers conj guess)))))




Saturday, November 3, 12
user> (guess-number secret-num)
                           Enter a guess between 1 and 10:   1
                           #{1}
                           user> (guess-number secret-num)
                           Enter a guess between 1 and 10:   2
                           #{1 2}
                           user> (guess-number secret-num)
                           Enter a guess between 1 and 10:   3
                           #{1 2 3}
                           ...
                           user> (guess-number secret-num)
                           Enter a guess between 1 and 10:   7
                           #{1 2 3 4 5 6 7}
                           user> (guess-number secret-num)
                           Enter a guess between 1 and 10:   8
                           #{1 2 3 4 5 6 7 8}
                           user> (guess-number secret-num)
                           Enter a guess between 1 and 10:   9
                           You guessed correctly

Saturday, November 3, 12
Atoms




Saturday, November 3, 12
(def picked-numbers (atom #{}))

   (def secret-num (.nextInt (java.util.Random.) 10))

   (defn guess-number [n]
     (print "Enter a guess between 1 and 10: ")
     (flush)
     (let [guess (java.lang.Integer/parseInt (read-line)) ]
       (cond
        (= guess n) (println "You guessed correctly")
        (contains? (deref picked-numbers) n) (println "Pick
   another number!")
        :else (swap! picked-numbers conj guess))))




Saturday, November 3, 12
Agents



Saturday, November 3, 12
user> (def some-agent (agent 0))
          #'user/some-agent
          user> (dotimes [i 100] (send some-agent inc))
          nil
          user> some-agent
          #<Agent@1997c457: 100>
          user> @some-agent
          100

Saturday, November 3, 12
Time is the new memory.
Saturday, November 3, 12
Звучи добре, ама дали
                  ще я бъде тая работа?
                    • Добри програмисти се изнасят на талази
                           към Clojure
                    • O’Reilly издадоха книга за Clojure!!!
                    • Thoughtbot съветва компаниите да
                           залагат на Clojure



Saturday, November 3, 12
Инструменти за
                           масово разрушение
                    • Leiningen 2
                    • Emacs
                    • clojure-mode
                    • paredit
                    • nrepl.el

Saturday, November 3, 12
Emacs Prelude включва всичко, което
                 ви трябва да програмирате на Clojure

                           https://github.com/bbatsov/prelude




Saturday, November 3, 12
Противотанкова
                             артилерия

                    • Eclipse (CounterClockWise)
                    • IntelliJ IDEA (LaClojure)
                    • NetBeans (Enclojure)


Saturday, November 3, 12
http://clojurekoans.org
Saturday, November 3, 12
Алтернативите




Saturday, November 3, 12
Simplicity is the
                   ultimate sophistication.
                                 Leonardo Da Vinci



Saturday, November 3, 12
Конец



Saturday, November 3, 12
Въпроси?



Saturday, November 3, 12

Más contenido relacionado

Último

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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 

Último (20)

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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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...
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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...
 

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Clojure: Return of the Jedi

  • 1. Episode VI: Clojure Завръщането на Джедаите Saturday, November 3, 12
  • 3. bozhidar user> (:twitter bozhidar) "@bbatsov" user> (bozhidar :blog) "http://batsov.com" user> (:github bozhidar) "http://github.com/bbatsov" Saturday, November 3, 12
  • 12. Затънали сме до уши в калта наречена “инцидентна сложност” и въобще не си даваме сметка за това... Saturday, November 3, 12
  • 13. public boolean hasUpperCase(String word) { if (word == null) { return false; } int len = word.length(); for (int i = 0; i < len; i++) { if (Character.isUpperCase(word.charAt(i))) { return true; } } return false; } (defn has-uppercase? [string] (some #(Character/isUpperCase %) string)) Saturday, November 3, 12
  • 14. Новото е добре забравено старо. Saturday, November 3, 12
  • 15. Конвенционален език за програмиране Saturday, November 3, 12
  • 16. Читав език за програмиране Saturday, November 3, 12
  • 17. Функционален език за програмиране Saturday, November 3, 12
  • 22. Магията на Lisp • Половин вековна история • Често имитиран, вечно ненадминат • Изключително малко ядро • Почти никакъв синтаксис • “Кодът е данни” (code is data) • Интерактивно програмиране Saturday, November 3, 12
  • 23. Проблемите на Lisp (Common Lisp/Scheme) • Никаква иновация след стандартизирането им • Сегментация • Думата “едновременно” (concurrently) не се споменава в спецификациите им • Повечето Lisp-ове дефинират сами своята платформа Saturday, November 3, 12
  • 24. Истинските мъже не ги е страх от малко скоби! Saturday, November 3, 12
  • 25. Хората имат неприятния навик да бъркат думите “познато” и “интуитивно”. Saturday, November 3, 12
  • 26. "We were after the C++ programmers. We managed to drag a lot of them about halfway to Lisp." Saturday, November 3, 12
  • 27. Ruby was a Lisp originally, in theory. “Ruby was a Lisp originally, in theory.” Saturday, November 3, 12
  • 28. Голяма част от езиците, които стават за нещо са повлияни пряко или косвено от Lisp!!! Saturday, November 3, 12
  • 30. A language that doesn’t affect the way you think about programming is not worth knowing. Saturday, November 3, 12
  • 32. Есенцията • Динамичен език за програмиране • JVM/CLR/JavaScript • Модерен диалеакт на Lisp (1) • Функционален по практичен начин • Оптимизиран за паралелно програмиране • Борец за един по-прост свят Saturday, November 3, 12
  • 33. Еволюцията на Lisp • сбогом car & cdr (hello first & rest) • по-малко скоби • повече структури от данни с literal синтаксис (set, map, vector) • коварно бърз runtime • стандартизиран runtime • непроменими (immutable) структури данни Saturday, November 3, 12
  • 34. (hello clojure) (defn hello-world [] (println "Hello, world!")) (defn hello [name] (println (format "Hello, %s!" name))) Saturday, November 3, 12
  • 35. user> (hello-world) Hello, world! nil user> (hello "Bozhidar") Hello, Bozhidar! nil Saturday, November 3, 12
  • 36. Lisp programmers know the value of everything, but the cost of nothing. Saturday, November 3, 12
  • 37. Структури от данни • свързан списък (list) • множество (set) • вектор • асоциативен масив (map/dictionary) • всичко Джавешко и родно Saturday, November 3, 12
  • 39. user> (list 1 2 3) (1 2 3) user> '(1 2 3) (1 2 3) user> (def names '("Bozhidar" "Snezhi" "Batman" "Yoda" "Mike")) #'user/names user> (first names) "Bozhidar" user> (rest names) ("Snezhi" "Batman" "Yoda" "Mike") user> (last names) "Mike" user> (count names) 5 user> (map lower-case names) ("bozhidar" "snezhi" "batman" "yoda" "mike") user> (map count names) (8 6 6 4 4) user> (apply + (map count names)) 28 user> (cons "Pesho" names) ("Pesho" "Bozhidar" "Snezhi" "Batman" "Yoda" "Mike") user> names ("Bozhidar" "Snezhi" "Batman" "Yoda" "Mike") user> (conj names "Pesho") ("Pesho" "Bozhidar" "Snezhi" "Batman" "Yoda" "Mike") Saturday, November 3, 12
  • 40. Mutable state is the new spaghetti code. Saturday, November 3, 12
  • 41. user> (filter even? (range 1 10)) (2 4 6 8) user> (every? even? (range 1 10)) false user> (every? even? (filter even? (range 1 10))) true user> (map #(+ % 5) (range 1 10)) (6 7 8 9 10 11 12 13 14) user> (map (partial + 5) (range 1 10)) (6 7 8 9 10 11 12 13 14) user> (map (comp (partial * 2) (partial + 5)) (range 1 10)) (12 14 16 18 20 22 24 26 28) Saturday, November 3, 12
  • 42. user> (doc and) ------------------------- clojure.core/and ([] [x] [x & next]) Macro Evaluates exprs one at a time, from left to right. If a form returns logical false (nil or false), and returns that value and doesn't evaluate any of the other expressions, otherwise it returns the value of the last expr. (and) returns true. nil user> (source and) (defmacro and "Evaluates exprs one at a time, from left to right. If a form returns logical false (nil or false), and returns that value and doesn't evaluate any of the other expressions, otherwise it returns the value of the last expr. (and) returns true." {:added "1.0"} ([] true) ([x] x) ([x & next] `(let [and# ~x] (if and# (and ~@next) and#)))) nil Saturday, November 3, 12
  • 43. Множество (Set) Saturday, November 3, 12
  • 44. user> (set '(1 1 2 2 3 3)) #{1 2 3} user> (def a-set #{1 2 3 4 5}) #'user/a-set user> (contains? a-set 3) true user> (contains? a-set 9) false user> (conj a-set 5) #{1 2 3 4 5} user> (conj a-set 6) #{1 2 3 4 5 6} user> (use 'clojure.set) nil user> (intersection #{1 2 3} #{2 3 4}) #{2 3} user> (difference #{1 2 3} #{2 3 4}) #{1} user> (union #{1 2 3} #{2 3 4}) #{1 2 3 4} Saturday, November 3, 12
  • 45. Асоциативен масив (Map) Saturday, November 3, 12
  • 46. user> (hash-map 1 2 3 4) {1 2, 3 4} user> (hash-map "Batman" "Bruce Wayne" "Superman" "Clark Kent") {"Batman" "Bruce Wayne", "Superman" "Clark Kent"} user> {:batman "Bruce Wayne", :superman "Clark Kent"} {:superman "Clark Kent", :batman "Bruce Wayne"} user> (def a-map {:batman "Bruce Wayne", :superman "Clark Kent"}) #'user/a-map user> (:superman a-map) "Clark Kent" user> (a-map :batman) "Bruce Wayne" user> (a-map :zorro) nil user> (merge a-map {:zorro "Diego de la Vega"}) {:superman "Clark Kent", :batman "Bruce Wayne", :zorro "Diego de la Vega"} user> a-map {:superman "Clark Kent", :batman "Bruce Wayne"} user> (contains? a-map :batman) true user> (assoc a-map :catwoman "Selina Kyle") {:superman "Clark Kent", :batman "Bruce Wayne", :catwoman "Selina Kyle"} user> a-map {:superman "Clark Kent", :batman "Bruce Wayne"} user> (dissoc a-map :batman) {:superman "Clark Kent"} user> a-map {:superman "Clark Kent", :batman "Bruce Wayne"} Saturday, November 3, 12
  • 47. Вектор (Vector) Saturday, November 3, 12
  • 48. user> (vector 1 2 3 4) [1 2 3 4] user> (into [] '(1 2 3 4)) [1 2 3 4] user> (def v (into [] (range 1 5))) #'user/v user> (count v) 4 user> (nth v 0) 1 user> (conj v 5) [1 2 3 4 5] user> (pop v) [1 2 3] user> (peek v) 4 user> [1 2 3 4] [1 2 3 4] Saturday, November 3, 12
  • 50. Идентичност и състояние Saturday, November 3, 12
  • 51. Паралелно програмиране Saturday, November 3, 12
  • 52. Законът на Мур даде фира в последните години Saturday, November 3, 12
  • 53. Процесорите днес са масово многоядрени. Saturday, November 3, 12
  • 54. Програмистите днес пишат масово single- threaded(process) софтуер! Saturday, November 3, 12
  • 55. Защо така бе, юнаци? Saturday, November 3, 12
  • 57. Сложно паралелното програмиране е! Saturday, November 3, 12
  • 59. user> (def f (future (Thread/sleep 10000) (println "done") 100)) #'user/f user> f #<core$future_call$reify__5684@201075c5: :pending> user> @f done 100 user> @f 100 user> (def my-delay (delay (println "did some work") 100)) #'user/my-delay user> @my-delay did some work 100 user> @my-delay 100 Saturday, November 3, 12
  • 60. Паралелни операции върху колекции Saturday, November 3, 12
  • 61. user> (defn slow-op [n] (Thread/sleep 5000) n) #'user/slow-op user> (map slow-op (range 1 5)) (1 2 3 4) user> (time (doall (map slow-op (range 1 5)))) "Elapsed time: 20004.081 msecs" (1 2 3 4) user> (time (doall (pmap slow-op (range 1 5)))) "Elapsed time: 5002.705 msecs" (1 2 3 4) Saturday, November 3, 12
  • 63. (def picked-numbers (ref #{})) (def secret-num (.nextInt (java.util.Random.) 10)) (defn guess-number [n] (print "Enter a guess between 1 and 10: ") (flush) (let [guess (java.lang.Integer/parseInt (read-line)) ] (cond (= guess n) (println "You guessed correctly") (contains? (deref picked-numbers) n) (println "Pick another number!") :else (dosync (alter picked-numbers conj guess))))) Saturday, November 3, 12
  • 64. user> (guess-number secret-num) Enter a guess between 1 and 10: 1 #{1} user> (guess-number secret-num) Enter a guess between 1 and 10: 2 #{1 2} user> (guess-number secret-num) Enter a guess between 1 and 10: 3 #{1 2 3} ... user> (guess-number secret-num) Enter a guess between 1 and 10: 7 #{1 2 3 4 5 6 7} user> (guess-number secret-num) Enter a guess between 1 and 10: 8 #{1 2 3 4 5 6 7 8} user> (guess-number secret-num) Enter a guess between 1 and 10: 9 You guessed correctly Saturday, November 3, 12
  • 66. (def picked-numbers (atom #{})) (def secret-num (.nextInt (java.util.Random.) 10)) (defn guess-number [n] (print "Enter a guess between 1 and 10: ") (flush) (let [guess (java.lang.Integer/parseInt (read-line)) ] (cond (= guess n) (println "You guessed correctly") (contains? (deref picked-numbers) n) (println "Pick another number!") :else (swap! picked-numbers conj guess)))) Saturday, November 3, 12
  • 68. user> (def some-agent (agent 0)) #'user/some-agent user> (dotimes [i 100] (send some-agent inc)) nil user> some-agent #<Agent@1997c457: 100> user> @some-agent 100 Saturday, November 3, 12
  • 69. Time is the new memory. Saturday, November 3, 12
  • 70. Звучи добре, ама дали ще я бъде тая работа? • Добри програмисти се изнасят на талази към Clojure • O’Reilly издадоха книга за Clojure!!! • Thoughtbot съветва компаниите да залагат на Clojure Saturday, November 3, 12
  • 71. Инструменти за масово разрушение • Leiningen 2 • Emacs • clojure-mode • paredit • nrepl.el Saturday, November 3, 12
  • 72. Emacs Prelude включва всичко, което ви трябва да програмирате на Clojure https://github.com/bbatsov/prelude Saturday, November 3, 12
  • 73. Противотанкова артилерия • Eclipse (CounterClockWise) • IntelliJ IDEA (LaClojure) • NetBeans (Enclojure) Saturday, November 3, 12
  • 76. Simplicity is the ultimate sophistication. Leonardo Da Vinci Saturday, November 3, 12