| 1 | <h2>Full example</h2> |
| 2 | <pre><code> |
| 3 | ; This code is copied from https://learnxinyminutes.com/docs/clojure/ |
| 4 | |
| 5 | ; Comments start with semicolons. |
| 6 | |
| 7 | ; Clojure is written in "forms", which are just |
| 8 | ; lists of things inside parentheses, separated by whitespace. |
| 9 | ; |
| 10 | ; The clojure reader assumes that the first thing is a |
| 11 | ; function or macro to call, and the rest are arguments. |
| 12 | |
| 13 | ; The first call in a file should be ns, to set the namespace |
| 14 | (ns learnclojure) |
| 15 | |
| 16 | ; More basic examples: |
| 17 | |
| 18 | ; str will create a string out of all its arguments |
| 19 | (str "Hello" " " "World") ; => "Hello World" |
| 20 | |
| 21 | ; Math is straightforward |
| 22 | (+ 1 1) ; => 2 |
| 23 | (- 2 1) ; => 1 |
| 24 | (* 1 2) ; => 2 |
| 25 | (/ 2 1) ; => 2 |
| 26 | |
| 27 | ; Equality is = |
| 28 | (= 1 1) ; => true |
| 29 | (= 2 1) ; => false |
| 30 | |
| 31 | ; You need not for logic, too |
| 32 | (not true) ; => false |
| 33 | |
| 34 | ; Nesting forms works as you expect |
| 35 | (+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 |
| 36 | |
| 37 | ; Types |
| 38 | ;;;;;;;;;;;;; |
| 39 | |
| 40 | ; Clojure uses Java's object types for booleans, strings and numbers. |
| 41 | ; Use `class` to inspect them. |
| 42 | (class 1) ; Integer literals are java.lang.Long by default |
| 43 | (class 1.); Float literals are java.lang.Double |
| 44 | (class ""); Strings always double-quoted, and are java.lang.String |
| 45 | (class false) ; Booleans are java.lang.Boolean |
| 46 | (class nil); The "null" value is called nil |
| 47 | |
| 48 | ; If you want to create a literal list of data, use ' to stop it from |
| 49 | ; being evaluated |
| 50 | '(+ 1 2) ; => (+ 1 2) |
| 51 | ; (shorthand for (quote (+ 1 2))) |
| 52 | |
| 53 | ; You can eval a quoted list |
| 54 | (eval '(+ 1 2)) ; => 3 |
| 55 | |
| 56 | ; Collections & Sequences |
| 57 | ;;;;;;;;;;;;;;;;;;; |
| 58 | |
| 59 | ; Lists are linked-list data structures, while Vectors are array-backed. |
| 60 | ; Vectors and Lists are java classes too! |
| 61 | (class [1 2 3]); => clojure.lang.PersistentVector |
| 62 | (class '(1 2 3)); => clojure.lang.PersistentList |
| 63 | |
| 64 | ; A list would be written as just (1 2 3), but we have to quote |
| 65 | ; it to stop the reader thinking it's a function. |
| 66 | ; Also, (list 1 2 3) is the same as '(1 2 3) |
| 67 | |
| 68 | ; "Collections" are just groups of data |
| 69 | ; Both lists and vectors are collections: |
| 70 | (coll? '(1 2 3)) ; => true |
| 71 | (coll? [1 2 3]) ; => true |
| 72 | |
| 73 | ; "Sequences" (seqs) are abstract descriptions of lists of data. |
| 74 | ; Only lists are seqs. |
| 75 | (seq? '(1 2 3)) ; => true |
| 76 | (seq? [1 2 3]) ; => false |
| 77 | |
| 78 | ; A seq need only provide an entry when it is accessed. |
| 79 | ; So, seqs which can be lazy -- they can define infinite series: |
| 80 | (range 4) ; => (0 1 2 3) |
| 81 | (range) ; => (0 1 2 3 4 ...) (an infinite series) |
| 82 | (take 4 (range)) ; (0 1 2 3) |
| 83 | |
| 84 | ; Use cons to add an item to the beginning of a list or vector |
| 85 | (cons 4 [1 2 3]) ; => (4 1 2 3) |
| 86 | (cons 4 '(1 2 3)) ; => (4 1 2 3) |
| 87 | |
| 88 | ; Conj will add an item to a collection in the most efficient way. |
| 89 | ; For lists, they insert at the beginning. For vectors, they insert at the end. |
| 90 | (conj [1 2 3] 4) ; => [1 2 3 4] |
| 91 | (conj '(1 2 3) 4) ; => (4 1 2 3) |
| 92 | |
| 93 | ; Use concat to add lists or vectors together |
| 94 | (concat [1 2] '(3 4)) ; => (1 2 3 4) |
| 95 | |
| 96 | ; Use filter, map to interact with collections |
| 97 | (map inc [1 2 3]) ; => (2 3 4) |
| 98 | (filter even? [1 2 3]) ; => (2) |
| 99 | |
| 100 | ; Use reduce to reduce them |
| 101 | (reduce + [1 2 3 4]) |
| 102 | ; = (+ (+ (+ 1 2) 3) 4) |
| 103 | ; => 10 |
| 104 | |
| 105 | ; Reduce can take an initial-value argument too |
| 106 | (reduce conj [] '(3 2 1)) |
| 107 | ; = (conj (conj (conj [] 3) 2) 1) |
| 108 | ; => [3 2 1] |
| 109 | |
| 110 | ; Functions |
| 111 | ;;;;;;;;;;;;;;;;;;;;; |
| 112 | |
| 113 | ; Use fn to create new functions. A function always returns |
| 114 | ; its last statement. |
| 115 | (fn [] "Hello World") ; => fn |
| 116 | |
| 117 | ; (You need extra parens to call it) |
| 118 | ((fn [] "Hello World")) ; => "Hello World" |
| 119 | |
| 120 | ; You can create a var using def |
| 121 | (def x 1) |
| 122 | x ; => 1 |
| 123 | |
| 124 | ; Assign a function to a var |
| 125 | (def hello-world (fn [] "Hello World")) |
| 126 | (hello-world) ; => "Hello World" |
| 127 | |
| 128 | ; You can shorten this process by using defn |
| 129 | (defn hello-world [] "Hello World") |
| 130 | |
| 131 | ; The [] is the list of arguments for the function. |
| 132 | (defn hello [name] |
| 133 | (str "Hello " name)) |
| 134 | (hello "Steve") ; => "Hello Steve" |
| 135 | |
| 136 | ; You can also use this shorthand to create functions: |
| 137 | (def hello2 #(str "Hello " %1)) |
| 138 | (hello2 "Fanny") ; => "Hello Fanny" |
| 139 | |
| 140 | ; You can have multi-variadic functions, too |
| 141 | (defn hello3 |
| 142 | ([] "Hello World") |
| 143 | ([name] (str "Hello " name))) |
| 144 | (hello3 "Jake") ; => "Hello Jake" |
| 145 | (hello3) ; => "Hello World" |
| 146 | |
| 147 | ; Functions can pack extra arguments up in a seq for you |
| 148 | (defn count-args [& args] |
| 149 | (str "You passed " (count args) " args: " args)) |
| 150 | (count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" |
| 151 | |
| 152 | ; You can mix regular and packed arguments |
| 153 | (defn hello-count [name & args] |
| 154 | (str "Hello " name ", you passed " (count args) " extra args")) |
| 155 | (hello-count "Finn" 1 2 3) |
| 156 | ; => "Hello Finn, you passed 3 extra args" |
| 157 | |
| 158 | |
| 159 | ; Maps |
| 160 | ;;;;;;;;;; |
| 161 | |
| 162 | ; Hash maps and array maps share an interface. Hash maps have faster lookups |
| 163 | ; but don't retain key order. |
| 164 | (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap |
| 165 | (class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap |
| 166 | |
| 167 | ; Arraymaps will automatically become hashmaps through most operations |
| 168 | ; if they get big enough, so you don't need to worry. |
| 169 | |
| 170 | ; Maps can use any hashable type as a key, but usually keywords are best |
| 171 | ; Keywords are like strings with some efficiency bonuses |
| 172 | (class :a) ; => clojure.lang.Keyword |
| 173 | |
| 174 | (def stringmap {"a" 1, "b" 2, "c" 3}) |
| 175 | stringmap ; => {"a" 1, "b" 2, "c" 3} |
| 176 | |
| 177 | (def keymap {:a 1, :b 2, :c 3}) |
| 178 | keymap ; => {:a 1, :c 3, :b 2} |
| 179 | |
| 180 | ; By the way, commas are always treated as whitespace and do nothing. |
| 181 | |
| 182 | ; Retrieve a value from a map by calling it as a function |
| 183 | (stringmap "a") ; => 1 |
| 184 | (keymap :a) ; => 1 |
| 185 | |
| 186 | ; Keywords can be used to retrieve their value from a map, too! |
| 187 | (:b keymap) ; => 2 |
| 188 | |
| 189 | ; Don't try this with strings. |
| 190 | ;("a" stringmap) |
| 191 | ; => Exception: java.lang.String cannot be cast to clojure.lang.IFn |
| 192 | |
| 193 | ; Retrieving a non-present key returns nil |
| 194 | (stringmap "d") ; => nil |
| 195 | |
| 196 | ; Use assoc to add new keys to hash-maps |
| 197 | (def newkeymap (assoc keymap :d 4)) |
| 198 | newkeymap ; => {:a 1, :b 2, :c 3, :d 4} |
| 199 | |
| 200 | ; But remember, clojure types are immutable! |
| 201 | keymap ; => {:a 1, :b 2, :c 3} |
| 202 | |
| 203 | ; Use dissoc to remove keys |
| 204 | (dissoc keymap :a :b) ; => {:c 3} |
| 205 | |
| 206 | ; Sets |
| 207 | ;;;;;; |
| 208 | |
| 209 | (class #{1 2 3}) ; => clojure.lang.PersistentHashSet |
| 210 | (set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} |
| 211 | |
| 212 | ; Add a member with conj |
| 213 | (conj #{1 2 3} 4) ; => #{1 2 3 4} |
| 214 | |
| 215 | ; Remove one with disj |
| 216 | (disj #{1 2 3} 1) ; => #{2 3} |
| 217 | |
| 218 | ; Test for existence by using the set as a function: |
| 219 | (#{1 2 3} 1) ; => 1 |
| 220 | (#{1 2 3} 4) ; => nil |
| 221 | |
| 222 | ; There are more functions in the clojure.sets namespace. |
| 223 | |
| 224 | ; Useful forms |
| 225 | ;;;;;;;;;;;;;;;;; |
| 226 | |
| 227 | ; Logic constructs in clojure are just macros, and look like |
| 228 | ; everything else |
| 229 | (if false "a" "b") ; => "b" |
| 230 | (if false "a") ; => nil |
| 231 | |
| 232 | ; Use let to create temporary bindings |
| 233 | (let [a 1 b 2] |
| 234 | (> a b)) ; => false |
| 235 | |
| 236 | ; Group statements together with do |
| 237 | (do |
| 238 | (print "Hello") |
| 239 | "World") ; => "World" (prints "Hello") |
| 240 | |
| 241 | ; Functions have an implicit do |
| 242 | (defn print-and-say-hello [name] |
| 243 | (print "Saying hello to " name) |
| 244 | (str "Hello " name)) |
| 245 | (print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") |
| 246 | |
| 247 | ; So does let |
| 248 | (let [name "Urkel"] |
| 249 | (print "Saying hello to " name) |
| 250 | (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") |
| 251 | |
| 252 | |
| 253 | ; Use the threading macros (-> and ->>) to express transformations of |
| 254 | ; data more clearly. |
| 255 | |
| 256 | ; The "Thread-first" macro (->) inserts into each form the result of |
| 257 | ; the previous, as the first argument (second item) |
| 258 | (-> |
| 259 | {:a 1 :b 2} |
| 260 | (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3) |
| 261 | (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b) |
| 262 | |
| 263 | ; This expression could be written as: |
| 264 | ; (dissoc (assoc {:a 1 :b 2} :c 3) :b) |
| 265 | ; and evaluates to {:a 1 :c 3} |
| 266 | |
| 267 | ; The double arrow does the same thing, but inserts the result of |
| 268 | ; each line at the *end* of the form. This is useful for collection |
| 269 | ; operations in particular: |
| 270 | (->> |
| 271 | (range 10) |
| 272 | (map inc) ;=> (map inc (range 10) |
| 273 | (filter odd?) ;=> (filter odd? (map inc (range 10)) |
| 274 | (into [])) ;=> (into [] (filter odd? (map inc (range 10))) |
| 275 | ; Result: [1 3 5 7 9] |
| 276 | |
| 277 | ; When you are in a situation where you want more freedom as where to |
| 278 | ; put the result of previous data transformations in an |
| 279 | ; expression, you can use the as-> macro. With it, you can assign a |
| 280 | ; specific name to transformations' output and use it as a |
| 281 | ; placeholder in your chained expressions: |
| 282 | |
| 283 | (as-> [1 2 3] input |
| 284 | (map inc input);=> You can use last transform's output at the last position |
| 285 | (nth input 2) ;=> and at the second position, in the same expression |
| 286 | (conj [4 5 6] input [8 9 10])) ;=> or in the middle ! |
| 287 | |
| 288 | |
| 289 | |
| 290 | ; Modules |
| 291 | ;;;;;;;;;;;;;;; |
| 292 | |
| 293 | ; Use "use" to get all functions from the module |
| 294 | (use 'clojure.set) |
| 295 | |
| 296 | ; Now we can use set operations |
| 297 | (intersection #{1 2 3} #{2 3 4}) ; => #{2 3} |
| 298 | (difference #{1 2 3} #{2 3 4}) ; => #{1} |
| 299 | |
| 300 | ; You can choose a subset of functions to import, too |
| 301 | (use '[clojure.set :only [intersection]]) |
| 302 | |
| 303 | ; Use require to import a module |
| 304 | (require 'clojure.string) |
| 305 | |
| 306 | ; Use / to call functions from a module |
| 307 | ; Here, the module is clojure.string and the function is blank? |
| 308 | (clojure.string/blank? "") ; => true |
| 309 | |
| 310 | ; You can give a module a shorter name on import |
| 311 | (require '[clojure.string :as str]) |
| 312 | (str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." |
| 313 | ; (#"" denotes a regular expression literal) |
| 314 | |
| 315 | ; You can use require (and use, but don't) from a namespace using :require. |
| 316 | ; You don't need to quote your modules if you do it this way. |
| 317 | (ns test |
| 318 | (:require |
| 319 | [clojure.string :as str] |
| 320 | [clojure.set :as set])) |
| 321 | |
| 322 | ; Java |
| 323 | ;;;;;;;;;;;;;;;;; |
| 324 | |
| 325 | ; Java has a huge and useful standard library, so |
| 326 | ; you'll want to learn how to get at it. |
| 327 | |
| 328 | ; Use import to load a java module |
| 329 | (import java.util.Date) |
| 330 | |
| 331 | ; You can import from an ns too. |
| 332 | (ns test |
| 333 | (:import java.util.Date |
| 334 | java.util.Calendar)) |
| 335 | |
| 336 | ; Use the class name with a "." at the end to make a new instance |
| 337 | (Date.) ; <a date object> |
| 338 | |
| 339 | ; Use . to call methods. Or, use the ".method" shortcut |
| 340 | (. (Date.) getTime) ; <a timestamp> |
| 341 | (.getTime (Date.)) ; exactly the same thing. |
| 342 | |
| 343 | ; Use / to call static methods |
| 344 | (System/currentTimeMillis) ; <a timestamp> (system is always present) |
| 345 | |
| 346 | ; Use doto to make dealing with (mutable) classes more tolerable |
| 347 | (import java.util.Calendar) |
| 348 | (doto (Calendar/getInstance) |
| 349 | (.set 2000 1 1 0 0 0) |
| 350 | .getTime) ; => A Date. set to 2000-01-01 00:00:00 |
| 351 | |
| 352 | ; STM |
| 353 | ;;;;;;;;;;;;;;;;; |
| 354 | |
| 355 | ; Software Transactional Memory is the mechanism clojure uses to handle |
| 356 | ; persistent state. There are a few constructs in clojure that use this. |
| 357 | |
| 358 | ; An atom is the simplest. Pass it an initial value |
| 359 | (def my-atom (atom {})) |
| 360 | |
| 361 | ; Update an atom with swap!. |
| 362 | ; swap! takes a function and calls it with the current value of the atom |
| 363 | ; as the first argument, and any trailing arguments as the second |
| 364 | (swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1) |
| 365 | (swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2) |
| 366 | |
| 367 | ; Use '@' to dereference the atom and get the value |
| 368 | my-atom ;=> Atom<#...> (Returns the Atom object) |
| 369 | @my-atom ; => {:a 1 :b 2} |
| 370 | |
| 371 | ; Here's a simple counter using an atom |
| 372 | (def counter (atom 0)) |
| 373 | (defn inc-counter [] |
| 374 | (swap! counter inc)) |
| 375 | |
| 376 | (inc-counter) |
| 377 | (inc-counter) |
| 378 | (inc-counter) |
| 379 | (inc-counter) |
| 380 | (inc-counter) |
| 381 | |
| 382 | @counter ; => 5 |
| 383 | |
| 384 | ; Other STM constructs are refs and agents. |
| 385 | ; Refs: http://clojure.org/refs |
| 386 | ; Agents: http://clojure.org/agents</code></pre> |