'Getting' Clojure - '(parentheses are just hugs for your code)

3,515 views
3,311 views

Published on

http://gtrak.github.io/bohconf.clojure

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,515
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
6
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

'Getting' Clojure - '(parentheses are just hugs for your code)

  1. 1. 'GETTING' CLOJURE'GETTING' CLOJURE '(PARENTHESES ARE JUST HUGS FOR YOUR CODE)'(PARENTHESES ARE JUST HUGS FOR YOUR CODE) Created by /Jason Lewis Gary Trakhman
  2. 2. Javascript             function(){               return 5;             }            FUNCTIONSFUNCTIONS
  3. 3. Put some parens around it, kill the braces             (function()               return 5;               )           
  4. 4. Change 'function' to 'fn', makes args into a vector             (fn []               return 5;               )           
  5. 5. Kill the 'return', last thing's always returned. Welcome to Clojure.             (fn [] 5)           
  6. 6. Move the left parenthesis over a bit more... Done.             someFunction(arg1, arg2, arg3);                        (someFunction arg1 arg2 arg3)            CALLING STUFFCALLING STUFF
  7. 7. THIS ISN'T AN ACCIDENTTHIS ISN'T AN ACCIDENT Javascript is 'Lisp in C's Clothing' Says Crockford: http://www.crockford.com/javascript/javascript.html
  8. 8. PUT ANOTHER WAY...PUT ANOTHER WAY... Q: Why do you think we've gotten so much mileage out of javascript? A: Lisp is very powerful, and it will never die
  9. 9. Should look familiar Don't freak out DON'T FREAK OUT {:key1 5,  :key2 nil} [1 2 3 4 "five"]            [1 [2] #{3} {4 4} (constantly 5)]            => (range 10) (0 1 2 3 4 5 6 7 8 9) => (take 11 (range)) (0 1 2 3 4 5 6 7 8 9 10) => (last (range)) ;;Hope you don't mind waiting a long time.            DATADATA
  10. 10. Evals to... ;; semicolons are comments, commas are ignored, ;; check out this weird hash­map {:a­keyword 5,  "a string key" "a string value",  ["a" :vector "acting" :as [:a :compound] "key"]  (fn [] "a no­arg function that returns this multi­line string, the function itself is the value"),  + '(functions can be keys too, and when you quote symbols, you just have symbols, not what they represent)}            {:a­keyword 5, "a string key" "a string value", ["a" :vector "acting" :as [:a :compound] "key"] #<user$eval331$fn__332 user$eval331$fn__332@a585ef>, #<core$_PLUS_ clojure.core$_PLUS_@20a12d8f> (functions can be keys too and when you quote symbols  you just have symbols not what they represent)}            EVERYTHING IS DATAEVERYTHING IS DATA
  11. 11. ANYTHING CAN BE A KEY, BECAUSEANYTHING CAN BE A KEY, BECAUSE 1. Every object is also a 'value' 2. Values have true equality 3. Values Never Change (Immutability) 4. Without immutability, objects are just buckets in memory ...have you ever trusted a bucket with no values?
  12. 12. Q: Why is this big news? A: I can write code and rest assured that other parts of my program can't change the data that I'm working on. Q: But I thought every program is simply a short-lived http request handler that talks to a database? We just throw the program state out after every request! A: Well, that's one way to do it.
  13. 13. http://www.ibm.com/developerworks/library/wa-aj- multitier2/
  14. 14. NODE.JS...NODE.JS... http://www.andrerodrigues.me/isel- workshop/intro.html#/24
  15. 15. NODE.JS... IS NOTHING NEWNODE.JS... IS NOTHING NEW We can write our own loops Node.js assumes threaded programming is hard, and throws out the baby with the bath-water Threaded programming is hard without real 'Data' or 'Values' Composition of any sort is simpler with data
  16. 16. APPROXIMATING NODE.JSAPPROXIMATING NODE.JS 'Agents' are asynchronous queues, sharing threadpools to do work, storing the last value returned. (defn inc­last [val]   (conj val (inc (last val)))) ;; We make a sequence of 10 inc­last tasks, ;; then follow­up with a 'println' task (def tasks   (concat (repeat 10 inc­last)           [(fn [val]              (println val)              val)]))             
  17. 17. ;; starts off with a value of [0] (let [a (agent [0])]   (doseq [t tasks]     (send a t))) ;; prints: [0 1 2 3 4 5 6 7 8 9 10]            Agents are not values, they are mutable references with asynchronous semantics Clojure has other mutable references types, acting as 'containers' for values, for various use cases. Nothing prevents you from making your own.
  18. 18. (let [f (future (do­a­bunch­of­stuff))] ;; in another thread   (do­stuff­in­this­thread)   ;; return the value in f, blocking if it's not finished   (deref f))          MORE!MORE! Basically, Clojure promotes your ability to do whatever you want, by simplifying things to their bare essence.
  19. 19. WHAT WE REALLY WANTWHAT WE REALLY WANT Tools that let us 1. Compose Systems 2. Change our minds 3. Re-use components in different contexts, processes, servers, etc.. Data/Values give us the ability to decouple things easily
  20. 20. '(code is data) BRAINSPLODEBRAINSPLODE
  21. 21. Read-Eval-Print-Loop (class (read­string "(+ 1 2)")) ;; clojure.lang.PersistentList (map class (read­string "(+ 1 2)")) ;; (clojure.lang.Symbol java.lang.Long java.lang.Long)            R-E-P-LR-E-P-L 1. Read: (read-string "(+ 1 2)") => '(+ 1 2) 2. Eval: (eval '(+ 1 2)) => 3 3. What if there's something in the middle?
  22. 22. This is only the beginning (defn only­even!  [val]  (if (and (integer? val) (odd? val))    (inc val)    val)) (map only­even! (read­string "(+ 1 2)")) ;; '(+ 2 2) (eval (map only­even! (read­string "(+ 1 2)"))) ;; 4           
  23. 23. Everybody likes chaining, right? How is this implemented? Is this reusable? $("#p1").css("color","red").slideUp(2000).slideDown(2000);           
  24. 24. What if, as a library author, you could just not write that fluent interface code at all? (use 'clojure.string) ;; These are equivalent (map trim (split (upper­case "hola, world") #",")) ;; ("HOLA" "WORLD") (­> "hola, world"     upper­case     (split #",")     (­>> (map trim))) ;; ("HOLA" "WORLD")           
  25. 25. Really useful when you're doing a lot of collection operations, filtering, etc. (­>> (range)      (filter even?)      (map (partial * 2))      (take 10)      (into [])) ;; [0 4 8 12 16 20 24 28 32 36] ;; versus (into []       (take 10 (map (partial * 2)                     (filter even? (range)))))            1. I find the flat one easier to think about. 2. Semantically equivalent. 3. No burden on implementing code. Functions don't care about how they're used. Giving the user choices is more effective with more powerful languages. Leads to simple, composable libraries.
  26. 26. Let's look at a real one. (defmacro lazy­seq   "Takes a body of expressions that returns an ISeq or nil, and yields   a Seqable object that will invoke the body only the first time seq   is called, and will cache the result and return it on all subsequent   seq calls. See also ­ realized?"   {:added "1.0"}   [& body]   (list 'new 'clojure.lang.LazySeq (list* '^{:once true} fn* [] body))) ;; simply returns a list, allocates a Java object (LazySeq) and wraps ;; your expressions in a function (macroexpand­1 '(lazy­seq ANYTHING1 ANYTHING2)) ;; '(new clojure.lang.LazySeq (fn* [] ANYTHING1 ANYTHING2))            MACROSMACROS
  27. 27. Let's create an infinite sequence representing a square-wave --__--__--__--__ No mutable variables (defn square­wave   "t is the period for a half­cycle"   [t]   (letfn     [(osc [cur­value so­far]        (let [so­far (mod so­far t)              next­val (if (zero? so­far)                         (­ cur­value)                         cur­value)]          (cons next­val                (lazy­seq (osc next­val                               (inc so­far))))))]     (osc 1 0)))            (take 10 (square­wave 3)) ;; (­1 ­1 ­1 1 1 1 ­1 ­1 ­1 1)           
  28. 28. CALL TO ACTIONCALL TO ACTION 1. Learn Clojure 2. Build cool things 3. Screencasts! (You ruby guys really know how to make good screencasts)
  29. 29. DEMO TIMEDEMO TIME CLOJURE ON THE WEBCLOJURE ON THE WEB Now clone this: https://github.com/canweriotnow/bohjure
  30. 30. RESOURCESRESOURCES Clojure: http://clojure.org Fun Exercises: http://www.4clojure.com Cheatsheets: http://clojure.org/cheatsheet Building: https://github.com/technomancy/leiningen Insight: http://www.youtube.com/user/ClojureTV Community docs: http://clojuredocs.org Blogs: http://planet.clojure.in Light Table: http://www.lighttable.com this doc: http://gtrak.github.io/bohconf.clojure
  31. 31. MORE DEMO TIMEMORE DEMO TIME
  32. 32. THANKS FOR COMING!THANKS FOR COMING! WE ARE:WE ARE: Gary Trakhman Software Engineer at @gtrakGT Revelytix, Inc. Jason Lewis CTO at @canweriotnow An Estuary, LLC

×