(gentle (introduction Clojure))

860 views

Published on

My introduction to Clojure given to the Scala User's Group in Johannesburg

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

  • Be the first to like this

No Downloads
Views
Total views
860
On SlideShare
0
From Embeds
0
Number of Embeds
73
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

(gentle (introduction Clojure))

  1. 1. A gentle introduction to Clojure (gentle (introduce Clojure)) - Talking with a LISP By /GuyTaylor @xsyn
  2. 2. (def @xsyn) Ok, so who am I and whydo I know anything? I don't... I've been playingwith Clojure for about3 years now -Making me aClojure blue belt. I'm afreelancer, currentlybuildingan analytics cluster for TYME, amobile bankingsolutions provider. I'm the father of 5 month old twins (SoIknowathingortwoaboutconcurrency) .
  3. 3. (def introduction) “If you wanteverything to be familiar, you will never learn anything new, because itcan'tbe significantly differentfromwhatyou already know and notdriftaway fromthe familiarity.” Rich Hickey Sure...butwhyClojure? Let's startbyidentifyingwhatitis
  4. 4. (clojure.set/intersection Clojure Scala) Clojure and Scalaare similiar in anumber of ways Functionallanguage Hosted on the JVM Javainterop
  5. 5. (clojure.set/difference Clojure Scala) Dynamicallytyped Enforced immutability It's aLISPOMG!WTF?Brackets?!Interrobang!
  6. 6. (def immutability) The hardest button to button...until..
  7. 7. The entire LISP universe is based around the followingstructure: (def LISP) (verbnounnoun)
  8. 8. (so? Clojure) LISPs are awesome Reallycooltooling I've never had so much fun with aprogramminglanguage Worth the personalgrowth
  9. 9. (def scalar-literals) Characters c;Character (classc);=java.lang.Character space newline formfeed return backspace tab Strings "hello";String (class"hello");=java.lang.String ;BUTstringsarealsocollections.Whichmeansthatanythingyoucan ;dotoacollectionyoucandotoastring.Holdthatthought...
  10. 10. (def scalar-literals) Numbers 42,0xff,2r111,040; long(64bitsignedinteger) 3.14,6.02139864;double(64bitfloatingpointdecimal) 42N;clojure.lang.BigInt(arbitaryprecisioninteger) 0.01M;java.math.BigDecimal(arbitaryprecisionsignedfloatingpointdecimal) 22/7;clojure.lang.Ratio
  11. 11. (def scalar-literals) Booleans nil;nil true;true false;false (=true1);false (=falsenil);false
  12. 12. Prettystraightfoward, buttheywork in verydifferentways. (def collection-literals) '(ab:name2);list [ab:name2];vector #{123};set {:nameGuy:nickxsyn};map
  13. 13. Lists are notused as frequentlyas other Clojure collection types. (def collection-literals) Lists '(123);(123) (list123);(123) (conj4(123);(4123) (first'(123));1 (second'(123));2 (nth'(123)2);3 ;;Readinalinearorder,NOTindexed,usefulforsmallcollections ;;Internallystoredasachainofvalues
  14. 14. Lists are notused as frequentlyas other Clojure collection types. (def collection-literals) Vectors [123];[123] (vec'(123));[123] (conj4(123);[1234] (next[123]);[23] (='(123)[123]);true ;;Indexed,goodforlargecollections,morefrequentlyusedthanlists ;;Internallystoredastrees
  15. 15. (def collection-literals) Sets #{123};#{123} (set[111222333]);#{123} (clojure.set/union#{123}#{45});#{12345} (clojure.set/difference#{123}#{23});#{1} (clojure.set/intersection#{123}#{23});#{23} ;;Uniqueitemsinset,mathematicalsets
  16. 16. (def collection-literals) Maps {:name"Guy":nick"xsyn":age34};{:age34,:name"Guy",:nick"xsyn"} (defxsyn{:name"Guy":nick"xsyn":age34});#'/xsyn (keysxsyn);(:age:name:nick) (valsxsyn);(34"Guy""xsyn") (getxsyn:name};("Guy") (:namexsyn);("Guy") (mergexsyn {:languages{:clojuretrue :scalafalse})) ;{:name"Guy":nick"xsyn":age34:languages{:clojure ;true:scalafalse} (get-in{:name"Guy":nick"xsyn":age34:languages{:clojure true:scalafalse}[:nick:languages]} (get-inxsyn[:languages:scala]);nil (get-in{:name"Guy":nick"xsyn":age34:languages{:clojuretrue :scalatrue}}[:languages:clojure]);true ;;Donotretainsequence
  17. 17. (def PersistentVector) (defbrown[012345678]) (defblue(assocbrown5'beef)) Source: http://hypirion.com/musings/understanding-persistent- vector-pt-1
  18. 18. (defn f [x] (f x)) Functions are the verbs of Clojure, everythingyou do you do through f [x]. (defncount-to-infinity[number] "Printnumberstoinfinity.Youshouldprobablynotrunthis" (printlncount-to-infinity(incnumber))) (defnfibs[] "Fibonnacisequencedemofunction" (mapfirst (iterate (fn[[ab]][b(+ab)])[01]))) Functions turn values into values.
  19. 19. (defmacro f [x] (f x)) Macros turn code into code. (defmacroignore "Cancelstheevaluationofanexpression,returningnilinstead." [expr] nil) user=>(ignore(+12)) nil
  20. 20. (ns foo.bar) Mappings from symbols to vars and classes (nsdata.core (:use[incanter.core] [incanter.io] [incanter.charts] [data.helpers] [clj-time.format:ast])) (defndatemap[date] "Dateformatter" (parse(t/formatter"YY/MM/dd")date))
  21. 21. (.interop Java) (defnfetch-url[address] (with-open[stream(.openStream(java.net.URL.address))] (let [buf(java.io.BufferedReader. (java.io.InputStreamReader.stream))] (applystr(line-seqbuf))))) #'user/fetch-url user=>(fetch-url"http://google.com") "<!doctypehtml>... ...</html>" ;;ImportingJavalibraries (import'(java.ioFileReader))
  22. 22. Leiningen for automating Clojure projects without setting your hair on fire
  23. 23. Building a project $leinnewfoobar Generatingaprojectcalledfoobarbasedonthe'default'template. Toseeothertemplates(app,leinplugin,etc),try`leinhelpnew`. $cdfoobar&&ls LICENSE README.md doc project.cljresources src test
  24. 24. Boilerplate Project.clj (defprojectfoobar"0.1.0-SNAPSHOT" :description"FIXME:writedescription" :url"http://example.com/FIXME" :license{:name"EclipsePublicLicense" :url"http://www.eclipse.org/legal/epl-v10.html"} :dependencies[[org.clojure/clojure"1.5.1"]])
  25. 25. Actual Project.clj (defprojectdata"0.1-alpha" :description"Datashuntingplayground" :license{:name"EclipsePublicLicense" :url"http://www.eclipse.org/legal/epl-v10.html"} :dependencies[[org.clojure/clojure"1.5.1"] [incanter/incanter-core"1.5.4"] [incanter/incanter-io"1.5.4"] [incanter/incanter-charts"1.5.4"] [incanter/incanter-excel"1.5.4"] [clj-time"0.6.0"] [org.clojure/data.json"0.2.1"] [org.apache.hadoop/hadoop-core"1.1.2"] [org.clojure/data.csv"0.1.2"]] :maindata.core :jvm-opts["-Xmx6G""-server""-Djsse.enableSNIExtension=false"])
  26. 26. Source: (def ungoogleable) A bunch of symbols that you'll see, but will find hard to google Some Examples: #;TheDispatchMacro #{;Thesetmacro,we'vealreadyseenthis #_;Thediscardmacro #";Theregularexpressionmacro #(;Thefunctionmacro #';Thevarmacro %;Argumentplaceholder @;Derefmacro ^;Metadata http://yobriefca.se/blog/2014/05/19/the-weird-and- wonderful-characters-of-clojure
  27. 27. (lazy-seq (doc introductions)) Books Clojure Programming-Chas Emerick The Joyof Clojure -MichaelFogus
  28. 28. (lazy-seq (doc introductions)) Videos http://www.infoq.com/author/Rich-Hickey Are we there yet-Rich Hickey The value of values -Rich Hickey Simple made easy-Rich Hickey While these are videos are byClojure's author, theyshine light on the philisophicalunderpinnings of Clojure, and are worth watchingeven if you never touch it.
  29. 29. (lazy-seq (doc introductions)) Online Clojure-Koans: http://clojurekoans.com Aphyr’s Clojure from the ground up: http://aphyr.com/posts/301-clojure-from-the-ground-up- welcome IRC: freenode.irc.net-#Clojure #Clojure.za BUILD SOMETHING
  30. 30. (questions? presentation) (thank you) (follow @xsyn) Presentation available on Github at: https://github.com/xsyn/intro-to-clojure

×