{"id":19659051,"url":"https://github.com/mbonaci/clojure","last_synced_at":"2025-07-14T00:36:24.510Z","repository":{"id":12782560,"uuid":"15456162","full_name":"mbonaci/clojure","owner":"mbonaci","description":"Java developer sneaks up on Clojure","archived":false,"fork":false,"pushed_at":"2020-03-01T07:37:40.000Z","size":2814,"stargazers_count":84,"open_issues_count":2,"forks_count":5,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-05T10:41:32.950Z","etag":null,"topics":["clojure"],"latest_commit_sha":null,"homepage":"http://mbonaci.github.io/clojure","language":"Clojure","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mbonaci.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-12-26T16:31:34.000Z","updated_at":"2025-03-04T10:40:43.000Z","dependencies_parsed_at":"2022-09-05T23:40:26.712Z","dependency_job_id":null,"html_url":"https://github.com/mbonaci/clojure","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mbonaci%2Fclojure","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mbonaci%2Fclojure/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mbonaci%2Fclojure/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mbonaci%2Fclojure/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mbonaci","download_url":"https://codeload.github.com/mbonaci/clojure/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251383755,"owners_count":21580930,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clojure"],"created_at":"2024-11-11T15:40:40.491Z","updated_at":"2025-04-28T20:31:42.583Z","avatar_url":"https://github.com/mbonaci.png","language":"Clojure","funding_links":[],"categories":[],"sub_categories":[],"readme":"*Written in January 2014, with Clojure 1.5.1 and Leiningen 2.3.4 on Java 1.7.0_45.*  \n_Inspired by Aphyr's excellent, Clojure from-the-ground-up tutorial and made possible by \"The joy of Clojure\" book. I also heavily used great \"Clojure for Java programmers\" talks by Rich Hickey, father of Clojure._  \n\n_Inspired? Made possible? Who am I kidding, I flat out stole from those kind people._\n\n\n## Clojure? That's a Lisp, for God's sake!\n\nI've been avoiding Clojure for a _long time_. Because it's a _Lisp dialect_ and I have a negative Lisp experience from school. It was either a bad timing or a bad teacher, I guess.  \nHmm, I guess my guessing about it, in itself, implies the answer :) \n\n\u003e Times and times again it gets apparent to me. Late puberty and adolescence are not the right times to go wide with programming languages!\n\n# :)\n### It must had something to do with the way the book was written\n\nMy renewed interest in Clojure was due to a chance encounter. I stumbled upon Aphyr's (Kyle Kingsbury) fascinating [Jepsen series](http://aphyr.com/tags/jepsen), a blog about perils of uncertainty in distributed systems.  \n\nThere, Clojure looked terse and concise, yet expressive and simple. So I decided to give it a shot. I picked up [The joy of Clojure](http://joyofclojure.com), got in my sweatshirt, put on a headband, closed my wife and our two-month-old twins in the living room, slightly licked my finger and opened up the first page...\n\n\u003e After the initial discovery phase, as I was going through the book, I suddenly found myself infatuated with the language. It's beautifully uniform, consistent and simple (which is different from \"easy\", mind you). At that point, it has just spread out to me, ready to be gulped away. And that's a great feeling!\n\n### How would you describe Clojure?\n\nClojure prides itself in being a **dynamic functional programming language**.  \nIt is built on three great facilities, **immutable data, first-class functions and dynamic typing**.  \n\n**Immutable data** means that a function always produces the same output, given the same input and that functions are side-effects free (when a function is run, nothing changes outside that function). All collections are immutable by design. Immutability in Clojure is not optional, like for instance, in Scala.\n\n**First class functions** means that a variable can be bound to a function, that a function can be passed to another (higher-order) function or that it may be returned from a function. In short, function is data.\n\n**Dynamic typing** means that we don't declare types. Data types are resolved at runtime.\n\n\u003e So from now on, when we say \"modify\", \"add\", \"remove\", ... it really means - create a \"copy\", modify the copy and return a reference to that new object.\n\u003e But the word \"copy\" from the previous sentence doesn't stand for a full, brute-force copy. In order to provide immutability and still preserve the performance guarantees (big O notation), Clojure uses something called **Structural sharing**, which basically means that the data structure of the new object is built by creating references to the elements of the old object, varying only with respect to the modified elements (called **path copying**). \n\n\u003e To picture this, think of a tree that gets a new node. Nodes of the new tree simply point to nodes of the old tree, so that, consequently, only a single full-blown node object gets created.\n\n# Setup\n### Open PRs\n\n\u003cimg src=\"https://github.com/mbonaci/clojure/raw/master/resources/lein.jpg\"\n alt=\"Leiningen logo\" title=\"The man himself\" align=\"right\" /\u003e\n\n\u003e Disclaimer: I write this as I'm going through the book myself, so bear with me. Open pull requests as you see fit\n\nOK, that's more than enough BS (for now). Let's start by setting up our Clojure runtime environment.\n\nTo set it up, I suggest you use an excellent automation tool (dependency mgr, builder, test runner, packager, all-in-one) [Leiningen](http://leiningen.org/). \n\n\u003e Notice there's no \"installer\" in the list of features. That's because Clojure is just another _dependency_ of \"our project\".\n\nFor your convenience, here's a dead simple, step-by-step environment setup for Ubuntu ([other OS, sir?](http://leiningen.org/#install)):\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n```sh\ncd /usr/bin\nsudo curl -O https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein\nsudo chmod a+x lein\n ```\n\nLet me explain what we just did. \nFirst we fetched `lein` script with `curl`° into `/usr/bin`°°.\nWe made sure it's executable with `chmod`.\n\n°  Use `sudo apt-get install curl`, if you haven't installed it yet (doesn't come OOTB with Ubuntu).  \n°° You can use any other dir, as long as you make sure it's in your PATH (check with `echo $PATH`), which makes possible to run it from anywhere.\n\nLet's kick things off:\n\n```sh\ncd\nlein new scratch\n ```\n\nHere we used `lein new` to create a fresh Clojure project, based on the `scratch` template (_scratch_ - as in _scratch the surface_, I guess).\nLein, in turn, installed _rest of itself_ into `~/.lein/self-installs`.\n\nIn case you get stuck, visit [lein install instructions](http://leiningen.org/#install).  \nIf you want to know more, the official Leiningen tutorial can be found [right here](https://github.com/technomancy/leiningen/blob/master/doc/TUTORIAL.md).\n\nLovely! Now fire along:\n\n```sh\ncd scratch\nlein repl\n```\n\nBoom! We have our own working Clojure environment.\n\n![repl](https://github.com/mbonaci/clojure/raw/master/resources/repl.png)\n\nREPL is short for _Read Eval Print Loop_, which is like an interactive window into a Clojure program (similar to a JavaScript console in the browser or REPL in Node).\n\nNow when that's all sorted and you're eager to learn, let's see how Clojure code looks like...\n\n# Basics\n\nA valid Clojure expression consists of _numbers_, _symbols_, _lists_, _keywords_, _booleans_, _characters_, _functions_, _function calls_, _macros_ (wtf?), _strings_, _literal maps_, _vectors_, and _sets_. \n\nAll of those, except _symbols_ and _lists_, evaluate to themselves.  \n\nSymbols are similar to variables in other languages, which basically means that, when a symbol is encountered, compiler tries to find the value that the symbol was previously (hopefully) bound to, which is then used in place of the symbol.  \n\nLists take a special place in Clojure (after all, Lisp means **LIS**t **P**rocessing). They are the main building block of the language.\nLists start with a so called _operation form_:\n\n```clj\n(op ...)\n```\n\n`op` can be either:\n - one of very few _special operations_ (listed bellow)\n - a _macro_\n - an expression that yields a _function_\n\nFor instance, if the Clojure compiler encounters:\n\n```clj\n(my-fun some-expr)\n```\n\nit'll first try to resolve `my-fun`, which in our case, is a previously defined function that conceptually looks like this:\n\n```clj\n(def my-fun value-expr)\n```\n\nThen, it'll evaluate `some-expr` and invoke the `my-fun` function, passing in the result.\n\n\u003e so `my-fun` is a _symbol_ that is bound to a function definition\n\nFull list of **special operations**:\n\n```clojure\ndef     ;evaluates an expression and binds the result to a symbol\nif      ;conditional evaluation\nfn      ;defines a function\nlet     ;establishes a name in a local lexical scope\nloop    ;used for functional looping\nrecur   ;used to support recursion in functional looping\ndo      ;defines a block of statements\nnew     ;allocates a new java object\n.       ;used to access a java method\nthrow   ;same as in java\ntry     ;same as in java\nset!    ;re-binds a symbol\nquote   ;supresses evaluation of an expression (same as single quote, ')\nvar     ;provides a mechanism to refer to a mutable storage location inside a thread (?)\n```\n\nThe list above may contain some descriptions that may not be clear to you, but soon, if you stuck with it, it'll all get cleared. And that's a promise.\n\nHere's how a function invocation looks like:\n\n```clj\nuser=\u003e (inc 2)      ;\"increment 2\"\n3                   ;this is REPL output\n;=\u003e 3               ;which I'll write like this from now on\n\n; those three that begin with a semicolon are comments\n;;this one also, from that first semicolon to the end of the line. All the way here -\u003e\n```\n\n## Syntax\n\n### Prefix/Polish notation\n\n```clj\n;; intentionally skipping java semicolons\n\n;;------------------------------------\n;;     Java             Clojure\n;;------------------------------------\nint i = 5              (def i 5)\n;;------------------------------------\nif(x == 0)             (if (zero? x)\n  return y               y\nelse                     z)\n  return z \n;;------------------------------------\nx * y * z              (* x y z)\n;;------------------------------------\nfoo(x, y, z)           (foo x y z)\n;;------------------------------------\n```\n\nYou can try the following example in your REPL:\n\n```clj\n;skipping the 'user=\u003e' prompt from now on\n(+ 1 (- 5 2) (+ 3 4))\n;=\u003e 11\n```\n\n\u003e Uh, that looks somewhat weird, right?\n\nThis type of notation, inherited from Lisp, called a _prefix notation_ or _Polish notation_, may look weird at the first glance.  \n\nLet's back up a bit.  \nAll programming languages, in order to execute the source code, need to parse it first. \nIn most languages, the product of this code parsing is a so called _abstract syntax tree_ (_AST_), which is then fed into the compiler.  \n\nLet's see how that tree looks for the example at hand.  \nIn Java, the expression above would be written like this:\n\n```java\n1 + (5 - 2) + (3 + 4);   // parentheses left for clarity\n// 1 + 3 + 7\n// 11\n```\n\n... and the _AST_ would look like this:\n\n![ast](https://github.com/mbonaci/clojure/raw/master/resources/ast.png)\n\nAfter seeing what _AST_ (as the ideal structure for representing code) looks like, I argue that _prefix_ is the natural way of representing expressions.  \n\nWhen you think of it (really hard), as early as first grade maths, the only option we ever see is _infix_ notation, so that's what gets hardwired inside our brains.\n\nThat is why, IMO, the _Polish notation_ looks weird to us.\n\n\u003e prefix notation allows any number of arguments in an operation (infix only two). Moreover, it completely eliminates the problem of operator precedence  \n\n\u003e at this point I have to stress that this is my opinion after only a couple of weeks learning Clojure. I'm slightly affraid of what would happen to me after I explore all corners of the language :)\n\n### Clojure is different\n\nThis is how a program is executed in a traditional, java-style _edit-compile-run_ way:\n\n![ast](https://github.com/mbonaci/clojure/raw/master/resources/TraditionalEvaluation.png)\n\nIn Java (and it's similar in other traditional languages), the source code gets handed to the compiler, which compiles it to bytecode. The bytecode is then run on the JVM. If you need to change something in your code, e.g. fix a bug, you need to do the whole process all over again. Open up the source file, make some changes, compile the source code, then stop the whole program and finally send the new version of bytecode to the JVM to be executed.\n\nUh, we got over that hurdle. Now we confidently start our program but we soon notice that it's still not right. OK, we stop the whole program once more and then start it in a debug mode, carefully setting breakpoints along the way. But sometimes it's not that easy, or even possible to replicate the exact context where our bug has previously occurred.\n\n\u003e at work, we often used to spend a better half of our day in this iterative process, doing nothing. When you combine that with IBM's tooling, that becomes a nightmare. E.g. Rational IDE weighs more than a GB. Websphere application server takes ages to start. When a new developer needs to set up his environment, it has known to take a couple of days to wire all the stuff together. We are crazy! How on earth we got eased into this unproductive way of working.\n\n![ast](https://github.com/mbonaci/clojure/raw/master/resources/ClojureEvaluation.png)\n\nClojure's evaluation is much more dynamic, the code first goes to **Reader**, which takes the characters and turns them into Clojure data structures.\nThe Compiler never sees the source code, it compiles the data structures produced by the Reader to bytecode, which is then run on the JVM.\n\nSo what does this mean? Can such a seemingly subtle difference have a noticeable impact on our development process?  \n\nThe point is that, this way, we can hot-swap a part of the running code without stopping the program. \nThe source code doesn't have to come from a file. We can use REPL to connect to a running program and evaluate expressions on the fly.\n\nThe other benefit is that other programs can easily produce data structures, thus avoiding source code and Reader all together. That's the Clojure's secret sauce. It's what makes **macros** possible.  \nWhen _Evaluator_, while processing source code, encounters a _macro_ (i.e. a symbol that is bound to a _macro_), it stops executing that part of the program and sends it to that _macro_, a _little side-program_ that manipulates data structures, transforming them in some useful way and then returning that, extended data structures back to the Evaluator.\n\nThis is extremely powerful concept, which allows us to extend the language without waiting for Rich Hickey to do so. Overwhelming amount of things, that are built-into other languages, are just macros in Clojure. For instance:\n\n```clj\n(or x y)        ;'or' is a macro in Clojure \n\n;;after being extended by or macro, becomes:\n\n(let [or__158 x]\n  (if or__158 or__158 y))\n```\n\nDon't worry if _macros_ are not clear yet (I explained them rather poorly, I know), we'll dedicate the whole chapter to that powerful construct.\n\n# Basics (this time for real)\n\n## Scalar data types\n\nA scalar data type is the one that can only hold one value at a time (value of a number, symbol, keyword, string or a character).\n\n### Numeric types\n\nThe following examples of numeric expressions are trivial, so I suggest you try them out, in your REPL.\n\n```clj\n(type 3)\n;=\u003e java.lang.Long\n\nLong/MAX_VALUE\n;=\u003e 9223372036854775807\n\n(inc (bigint Long/MAX_VALUE))\n;=\u003e 9223372036854775808N\n\n(type 5N)\n;=\u003e clojure.lang.BigInt\n\n(type (int 0))\n;=\u003e java.lang.Integer\n\n(type (short 0))\n;=\u003e java.lang.Short\n\n(type (byte 0))\n;=\u003e java.lang.Byte\n\n;; decimal, hexadecimal, octal, radix-32, and binary literals:\n[127 0x7F 0177 32r3V 2r01111111]\n;=\u003e [127 127 127 127 127]\n;; radix supports up to base 36\n\n(Short/MAX_VALUE)\n;=\u003e 32767\n\n(Integer/MAX_VALUE)\n;=\u003e 2147483647\n\nByte/MAX_VALUE\n;=\u003e 127\n\n(type 1.23)\n;=\u003e java.lang.Double\n\n(type (float 1.23))\n;=\u003e java.lang.Float\n\n366e3\n;=\u003e 366000.0\n```\n\n\n```clj\n(+ 1 2.0)\n;=\u003e 3.0\n\n(class (+ 1 2.0))\n;=\u003e java.lang.Double\n\n(= 3 3.0)\n;=\u003e false\n\n(== 3 3.0)\n;=\u003e true\n\n(* 2 3 1/5)\n;=\u003e 6/5\n\n(- 5 1 1 1)\n;=\u003e 2\n\n(- 2)\n;=\u003e -2\n\n(* 4)\n;=\u003e 4\n\n(/ 4)\n;=\u003e 1/4\n\n(+)\n;=\u003e 0     ;neutral for addition\n\n(*)\n;=\u003e 1     ;neutral for multiplication\n\n(\u003c= 1 2 3)\n;=\u003e true\n\n(\u003c= 1 3 2)\n;=\u003e false\n\n(= 2 2 3)\n;=\u003e false\n\n(= 2 2 2)\n;=\u003e true\n```\n\nTo avoid having to round floating-point numbers (e.g. result of `2 / 3`), Clojure provides a **rational** number type `clojure.lang.Ratio`, thus maintaining absolute precision when dealing with floating point arithmetic:\n\n```clj\n(type 1/3)\n;=\u003e clojure.lang.Ratio\n\n;; rational numbers are automatically simplified, if possible:\n100/25\n;=\u003e 4\n\n(rational? 2)   ;is rational or may be rational\n;=\u003e true\n\n(rational? 2.1)\n;=\u003e false\n\n(rationalize 2.1)\n;=\u003e 21/10\n\n(numerator (/ 21 10))\n;=\u003e 21\n\n(denominator (/ 21 10))\n;=\u003e 10\n```\n\n\u003e The calculation of rational math, though accurate, isn’t nearly as fast as with floats or doubles (due to overhead cost of e.g. finding the least common denominator).\n\n**Truncation**\n\nTruncation is a process of limiting the accuracy of floating-point numbers, due to deficiencies in its representation. When a number is truncated, its precision is limited such that the maximum number of digits of accuracy is bound by the number of bits that can fit into the storage space allowed by its representation.\n\n```clj\n(let [pi-constant 3.14159265358979323846264338327950288419716939937M] ;notice the M\n  (println (class pi-constant))\n  pi-constant)\n;=\u003e java.math.BigDecimal\n;=\u003e 3.14159265358979323846264338327950288419716939937M\n\n(let [pi-trunc 3.14159265358979323846264338327950288419716939937]\n  (println (class pi-trunc))\n  pi-trunc)\n;=\u003e java.lang.Double\n;=\u003e 3.141592653589793\n```\n\n`M`, at the end of a floating-point number literal is used to tell Clojure to keep the number in its full precision.  \n`N` is used for the same thing when dealing with longs.\n\n\u003e Clojure truncates floating point numbers by default\n\n**Promotion**\n\nClojure is able to detect when overflow occurs. Then, it automatically promotes the value to a numerical representation that can accommodate larger values\n\n```clj\n(def small 9)\n(class small)\n;=\u003e java.lang.Long\n\n(class (+ small 90000000000000000000))\n;=\u003e clojure.lang.BigInt\n\n(class (+ small 9.0))\n;=\u003e java.lang.Double\n\n(+ Integer/MAX_VALUE Integer/MAX_VALUE)\n;=\u003e 4294967294\n\n(class (+ Integer/MAX_VALUE Integer/MAX_VALUE))\n;=\u003e java.lang.Long\n```\n\n\u003e There's no limit to integer size in Clojure, besides RAM size\n\n### Strings and Characters\n\nString is any sequence of characters enclosed in double quotes, including newlines:\n\n```clj\n\"this is a string\non two lines\"\n;=\u003e \"this is a string\\non two lines\"  ;REPL output includes newline escape\n\n(type \"a\")\n;=\u003e java.lang.String\n\n(str nil)    ;'nil' is Clojure's 'null'\n;=\u003e \"\"\n```\n\n\u003e single quote, backtick and `quote` (though with slightly different properties) are used to include literals in a program without evaluating them\n\n```clj\n(str 'cat)\n;=\u003e \"cat\"\n\n(str 'a')\n;=\u003e \"a'\"\n\n(str 1)\n;=\u003e \"1\"\n\n(str '1)\n;=\u003e \"1\"\n\n(str true)\n;=\u003e \"true\"\n\n(str '(1 2 3))\n;=\u003e \"(1 2 3)\"\n\n(str \"meow \" 3 \" times\")\n;=\u003e \"meow 3 times\"\n\n;characters are denoted by backslash\n\\a\n;=\u003e \\a\n\n\\u0042\n;=\u003e \\B\n\n\\\\\n;=\u003e \\\\\n```\n\n## Symbols\n\nSymbols can have either short or full names. The short name is used to refer to things locally, and the _fully qualified name_ is used to refer unambiguously to a symbol (from anywhere).\nSymbol names are separated with a `/`. For instance, the symbol `str` is also present in a namespace called `clojure.core` and the corresponding full name is `clojure.core/str`\nThe main purpose of symbols is to refer to _things_, i.e. to point to other values. When evaluating a program, symbols are looked up and replaced by their corresponding values. \n\n\u003e [more about symbols](#symbols)\n\n```clj\n(= str clojure.core/str)\n;=\u003e true\n\n(name 'clojure.core/str)\n;=\u003e \"str\"\n```\n\n\n## Keywords\n\nClosely related to symbols and strings are keywords, which begin with a `:`.  \nKeywords are like strings in that they are made up of text, but are specifically intended for use as labels or identifiers. These are not labels in the sense of symbols, keywords are not replaced by any other value, they are just names, by themselves:\n\n```clj\n(type :cat)\n;=\u003e clojure.lang.Keyword\n\n(str :cat)\n;=\u003e \":cat\"\n\n(name :cat)\n;=\u003e \"cat\"\n```\n\n**Using keywords as map keys**\n\n\u003e since keywords are self-evaluating and provide fast equality checks, they are almost always used as map keys\n\nAnother important property of keywords, when used as map keys, is that they can be used as functions, taking a map as an argument to perform value lookups:\n\n```clj\n(def mouse-planet {:cats 180, :mice 9})   ;define a map\n;=\u003e #'user/mouse-planet\n\n(:cats mouse-planet)                      ;lookup by keyword\n;=\u003e 180\n\n(println (/ (:cats mouse-planet)          ;much more useful example\n            (:mice mouse-planet))\n         \"cats per capita\")\n;=\u003e 20 cats per capita\n```\n\n**As enumerations**\n\nSince their value doesn't change, convenient keyword use case is enumeration. E.g. `:mouse`, `:rat` and `:x-rat` provide a nice visual delineation (for mouse types) within a source code.\n\n\u003e there are other useful things we can do with keywords. We can use them **As multimethod dispatch values** and **As directives**, but we'll deal with that later\n\n**Qualifying your keywords**\n\nKeywords don't belong to any specific namespace, although it's a good practice to define them as if they do, because that way you provide a context:\n\n```clj\nuser=\u003e :not-in-ns\n;=\u003e :not-in-ns\n\nuser=\u003e ::not-in-ns          ;fully qualified keyword\n;=\u003e :user/not-in-ns\n\nuser=\u003e (ns another)\n;=\u003e nil\n\nanother=\u003e :user/in-another  ;\"fully qualified\" keyword\n;=\u003e :user/in-another\n\nanother=\u003e :haunted/name     ;namespace doesn't have to exist\n;=\u003e :haunted/name\n```\n\n\u003e double colon is used to fully qualify a keyword by prepending the current namespace name to the keyword name\n\n\u003e equally named keywords are the same object in memory\n\n## Booleans\n\nOnly `false` and `nil` are logical `false`, all others values are `true`:\n\n```clj\n(boolean nil)\n;=\u003e false\n\n(boolean 0)\n;=\u003e true\n\n(boolean \"hi\")\n;=\u003e true\n\n(boolean str)\n;=\u003e true\n\n(and true false true)\n;=\u003e false\n\n(and true true true)\n;=\u003e true\n```\n\n... and returns the first _falsy_ value, or the last value if all are _truthy_:\n```clj\n(and 1 2 3)\n;=\u003e 3\n\n(and -1 nil 2)\n;=\u003e nil\n```\n\nor returns the first _truthy_ value, or the last value if all are _falsy_:\n```clj\n(or false 2 3)\n;=\u003e 2\n\n(or false false nil)\n;=\u003e nil\n```\n\n`not` inverses the _truthiness_ of the expression:\n```clj\n(not nil)\n;=\u003e true\n```\n\n## Regular expressions\n\n`#\"...\"` is Clojure’s way of writing a regular expression.  \nClojure and Java have very similar Regex syntax.\n\n```clj\n(re-find #\"cat\" \"mystic cat mouse\")\n;=\u003e \"cat\"\n\n(re-find #\"cat\" \"only dogs here\")\n;=\u003e nil\n```\n\nThe parentheses, i.e. _capturing group_ means that the regular expression should capture that part of the match. We get back a _list_ containing the part of the string that matched the first parentheses, followed by the part that matched the second parentheses, etc:\n\n```clj\n(re-matches #\"(.+):(.+)\" \"mouse:treat\")\n;=\u003e [\"mouse:treat\" \"mouse\" \"treat\"]\n\n;; capturing group in the regex causes each returned item to be a vector:\n(re-seq #\"\\w*(\\w)\" \"one-two/three\")\n;=\u003e ([\"one\" \"e\"] [\"two\" \"o\"] [\"three\" \"e\"])\n```\n\nJava's regex `Pattern` class has several methods that can be used directly, but only `split` is used regularly to split a string into an array of Strings:\n\n```clj\n(seq (.split #\",\" \"1,2,3,4\"))  ;this is how you call Java methods\n;=\u003e (\"1\" \"2\" \"3\" \"4\")\n```\n\n[Java interoperability section.](#java-interop)  \n\nThe `re-seq` function returns a lazy sequence of all matches in a string:\n\n```clj\n(re-seq #\"\\w+\" \"one-two/three\")\n;=\u003e (\"one\" \"two\" \"three\")\n```\n\n\u003e Java's regex engine includes a `Matcher` object which mutates in a non-thread-safe way as it walks through a string finding matches. This object is exposed in Clojure through the `re-matcher` function and can be used in combination with `re-groups` and `re-find`.\nIt's recommended to avoid direct usage of all of these three functions.\n\n# Collections\n\nA collection is a group of values. It’s a container which provides some structure, some framework, for the things that it holds. We refer to collection members as elements, or items.\n\nAll Clojure's collections support heterogeneous values (values of arbitrary types), together, in the same collection.\n\n\u003e when a collection is evaluated (except lists), each of its contained items is evaluated first\n\nMost of functions that work on collections aren't actually written to work on concrete collection types, but rather to work on abstract data types. For instance, some of abstractions in this space are:\n\n - Collection  (common to all concrete types)\n - Sequential  (ordered collections are lists and vectors)\n - Associative (maps associate keys with values, vectors associate indices with values)\n - Indexed     (vectors, for example, can be quickly indexed into)\n\n## Lists\n\nA `PersistentList` is a singly linked list where each node knows its distance from the end. \nList elements can only be found by starting with the first element and walking each prior node in order. \nList elements can only be added or removed from the left end.\n\nIn idiomatic Clojure code, lists are used almost exclusively to represent code forms, e.g. to call functions, macros, ...\nCode forms are then `eval`-ed or used as the return value for a macro.\n\n\u003e Lists are rarely used for anything other than to represent Clojure source code, because they rarely offer any value over vectors\n\nLiteral lists are written with parentheses: `(yankee hotel foxtrot)`.\n\nWhen a list is evaluated, the first item of the list, `yankee`, will be resolved to a _function_, _macro_, or _special form_. \nIf `yankee` is a _function_, the remaining items in the list will be evaluated in order, and the results will be passed to `yankee` as its parameters.\nIf `yankee` is a _macro_ or a _special form_, the remaining items in the list\naren’t necessarily evaluated, but are processed as defined by the _macro_ or _operator_.\n\n\u003e **special form** is a form with special syntax or special evaluation rules that are typically not implemented using the base Clojure forms. An example of a special form is\nthe `.` (dot) operator used for Java interoperability purposes.\n\n```clj\n(cons 1 (2 3))\n\n;=\u003e ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn\n;;which basically means that the number 2 cannot be used as a function\n\n(cons 1 '(2 3))\n;=\u003e (1 2 3)\n```\n\nRemember, we quote lists (and everything else that needs quoting) with a `'` (or `quote`) to prevent them from being evaluated.  \n\n```clj\n'(1 2 3)\n;=\u003e (1 2 3)\n\n(type '(1 2 3))\n;=\u003e clojure.lang.PersistentList\n```\n\nThere's also a **syntax-quote** (back-tick), which automatically qualifies all unqualified symbols in its argument:\n\n```clj\n`map\n;=\u003e clojure.core/map\n\n`(map even? [1 2 3])\n;=\u003e (clojure.core/map clojure.core/even? [1 2 3])\n```\n\nYou can also construct a list using `list`:\n\n```clj\n(list 1 2 3)\n(1 2 3)\n(= (list 1 2) (list 1 2))\ntrue\n```\n\nYou can modify a list by _conjoining_ an element onto it (as always with lists, the new element goes to the beginning):\n\n```clj\n(conj (list 1 2 3) 4)\n;=\u003e (4 1 2 3)\n\n(first (list 1 2 3))\n;=\u003e 1\n\n(second (list 1 2 3))\n;=\u003e 2\n\n(nth (list 1 2 3) 2)\n;=\u003e 3\n```\n\nUnlike some _Lisps_, the empty list in Clojure, `()`, isn't the same as `nil`.\nLists are well-suited for small collections, or collections which are read in linear order, but are slow when you want to get arbitrary elements from later in the list. \n\n\u003e Calling `seq` on a list returns the list itself, but more often, calling `seq` on a collection returns a new `seq` object for navigating that collection.\n\n### What lists aren't?\n\nProbably the most common misuse of lists is to hold items that will be looked up by index. Though you can use `nth` to get the element, Clojure will have to walk the list from the beginning to find it.  \n\nLists aren't queues. You can add items to one end, but you can't remove from the other.\n\n### PersistentQueue\n\nPersistent immutable queue is a FIFO structure where `conj` adds to the rear, `pop` removes from the front and `peek` returns the front element without removal.\n\nClojure currently doesn't provide a core construction function for creating persistent queues, but there's a readily available empty queue instance to use, `clojure.lang.PersistentQueue/EMPTY`.\n\nThe printed representation for Clojure's queues isn't particularly informative, but we can change that by providing a method for them on the `print-method`:\n\n```clj\n(defmethod print-method clojure.lang.PersistentQueue\n  [q, w]\n  (print-method '\u003c- w) (print-method (seq q) w) (print-method '-\u003c w))\n\nclojure.lang.PersistentQueue/EMPTY\n;=\u003e \u003c-nil-\u003c\n```\n\n\u003e Popping an empty queue results in just another empty queue. Peeking an empty queue returns `nil`\n\nThe mechanism for adding an element to a queue is `conj`:\n\n```clj\n(def tasks\n  (conj clojure.lang.PersistentQueue/EMPTY\n  :wake-up :shower :brush-teeth))\n;=\u003e #'mbo/tasks\n\ntasks\n;=\u003e \u003c-(:wake-up :shower :brush-teeth)-\u003c\n```\n\n\u003e Clojure's persistent queue is implemented internally using two separate collections, the front being a seq and the rear being a vector. All insertions occur in the rear vector and all removals occur in the front seq, taking advantage of each collection's strength. When all the items from the front have been popped, the back vector is wrapped in a seq to become the new front and an empty vector is used as the new back\n\nTo get the front element, we use `peek`:\n\n```clj\n(peek tasks)\n;=\u003e :wake-up\n```\n\nTo remove elements from the front of a queue, we use `pop` (although possible, it's non-idiomatic and suboptimal to use `rest` with queues, because it returns a seq, not a queue and _screws up_ the speed guarantees):\n\n```clj\n(pop tasks)       ;; returns new list, remember?\n;=\u003e \u003c-(:shower :brush-teeth)-\u003c\n\n(rest tasks)\n;=\u003e (:shower :brush-teeth)\n```\n\n## Vectors\n\nFor fast access to every element, we use a __vector__.\nVectors are surrounded by square brackets, just like lists are surrounded by parentheses. Because vectors aren’t evaluated like lists are, there is no need to quote the vector literal:\n\n```clj\n[1 2 3]\n;=\u003e [1 2 3]\n\n(type [1 2 3])\n;=\u003e clojure.lang.PersistentVector\n```\n\n\u003e Vectors are similar to arrays, but are immutable and persistent\n\nYou can also create vectors with `vector`, or change other structures into vectors with `vec`:\n\n```clj\n(vector 1 2 3)\n;=\u003e [1 2 3]\n\n(vec (list 1 2 3))\n;=\u003e [1 2 3]\n```\n\n`conj` on a vector adds to the end, not the start, like with lists:\n\n```clj\n(conj [1 2 3] 4)\n;=\u003e [1 2 3 4]\n```\n\nOur friends `first`, `second`, and `nth` work here too; but unlike lists, `nth` is fast on vectors. That’s because internally, vectors are represented as a very broad tree of elements, where each part of the tree branches into 32 smaller trees. Even very large vectors are only a few layers deep, which means getting to elements only takes a few hops, which is why retrieval operation from the interior of a vector takes essentially a constant time.\n\nThe important difference, when compared to lists, is that vectors evaluate each item in order. No function or macro is performed on a vector itself.\n\n`rest` and `next` both return _everything but the first element_. They differ only by what happens when there are no remaining elements:\n\n```clj\n(rest [1 2 3 4])\n;=\u003e (2 3 4)\n\n(next [1 2 3 4])\n;=\u003e (2 3 4)\n```\n\n`rest` returns logical `true`, `next` returns logical `false`. Each has their uses, but in almost every case they’re equivalent:\n\n```clj\n(next [1])\n;=\u003e nil\n\n(rest [1])\n;=\u003e ()\n```\n\n`last`, surprisingly, returns the last element:\n\n```clj\n(last [1 2 3])\n;=\u003e 3\n```\n\n`count`, shockingly, returns element count:\n\n```clj\n(count [1 2 3 4])\n;=\u003e 4\n```\n\nYou can use element's index to access it:\n\n```clj\n([1 2 3] 1)  ;vectors are in fact functions of their indices\n;=\u003e 2\n```\n\nVectors and lists containing the same elements are considered equal:\n\n```clj\n(= [1 2] (list 1 2))\n;=\u003e true\n```\n\nIf you already have a vector but want to \"pour\" several values into it, use `into`:\n\n```clj\n(let [m-vector [:a :b :c]]\n  (into m-vector (range 10)))\n;=\u003e [:a :b :c 0 1 2 3 4 5 6 7 8 9]\n\n;;if you want to return a vector the first arg to 'into' must be a vector\n;;the second argument must be anything that works with 'seq' function\n```\n\n### Primitive vectors\n\nYou can store primitive types inside of vectors using the `vector-of` function, which takes any of `:int`, `:long`, `:float`, `:double`, `:byte`, `:short`, `:boolean` and `:char` and returns an empty vector. This returned vector will act just like any other vector, except that, internally, it'll store its contents as primitives.  \nThe new vector will try to coerce any additions into its internal type when they are being added:\n\n```clj\n(into (vector-of :int) [Math/PI 2 1.3])\n;=\u003e [3 2 1]\n\n(into (vector-of :char) [100 101 102])\n;=\u003e [\\d \\e \\f]\n\n(into (vector-of :int) [1 2 609812734019519652839108477134])\n\n;=\u003e IllegalArgumentException Value out of range for long: 60981273401951...\n;=\u003e clojure.lang.RT.longCast (RT.java:1134)\n```\n\n### Large vectors\n\nVectors are particularly efficient at three things (relative to lists): \n - adding or removing things from the right end of the collection\n - accessing or changing items in the interior of the collection by numeric index\n - walking in reverse order\n\n```clj\n(def a-to-e (vec (map char (range 65 70))))\n;=\u003e #'mbo/a-to-z\n\na-to-e\n;=\u003e [\\A \\B \\C \\D \\E]\n\n(nth a-to-e 4)   ;like with a map\n;=\u003e \\E\n\n(get a-to-e 4)   ;like with a map\n;=\u003e \\E\n\n(a-to-e 4)       ;invoking a vector as a function\n;=\u003e \\E\n```\n\n![vector-lookup-options](https://github.com/mbonaci/clojure/raw/master/resources/vector-lookup-options.png)\n\nSince vectors are indexed, they can be efficiently walked in either direction. The `seq` and `rseq` return sequences that do exactly that:\n\n```clj\n(seq a-to-e)\n;=\u003e (\\A \\B \\C \\D \\E)\n\n(rseq a-to-e)\n;=\u003e (\\E \\D \\C \\B \\A)\n```\n\nAny item in a vector can be \"changed\" using the `assoc` function (in a constant time). Clojure does this using _structural sharing_ between the old and the new vectors, hence avoiding having to copy all the elements.\n\n```clj\n(assoc a-to-e 3 \"former D\")\n;=\u003e [\\A \\B \\C \"former D\" \\E]\n```\n\nThe `assoc` function works only on indices that either already exist or, as a special case, exactly one step past the end of a vector (returned vector becomes one item larger).\n\nFunction `replace` uses `assoc` internally:\n\n```clj\n(replace {2 :a, 4 :b} [1 2 3 2 3 4])\n;=\u003e [1 :a 3 :a 3 :b]\n```\n\nThe functions `assoc-in`, `update-in` and `get-in` are used to work with nested structures of vectors and/or maps. These functions take a series of indices to pick items from each more deeply nested level:\n\n```clj\n(def matrix\n  [[1 2 3]\n   [4 5 6]\n   [7 8 9]])\n;=\u003e #'mbo/matrix\n\n(get-in matrix [1 2])   ;second row, third column\n;=\u003e 6\n\n(assoc-in matrix [1 2] 'x)\n;=\u003e [[1 2 3] [4 5 x] [7 8 9]]\n```\n\n`update-in` works the similar way, but instead of taking a value to \"overwrite\" an existing value, it takes a function to _apply_ to an existing value. It'll replace the value at the given coordinates with the return value of the function:\n\n```clj\n(update-in matrix [1 2] * 100)\n;=\u003e [[1 2 3] [4 5 600] [7 8 9]]\n\n;; the coordinates refer to the value 6 and the function is * taking an argument 100\n;; so the slot becomes the return value of (* 6 100)\n```\n\nRemember? `matrix` itself never changed:\n\n```clj\nmatrix\n;=\u003e [[1 2 3] [4 5 6] [7 8 9]]\n```\n\n### Vectors as stacks\n\nClojure vectors uses `conj` as `push` and `pop` as `pop` to add and remove elements from the right side. Since vectors are immutable, `pop` returns a new vector with the rightmost element dropped, which is different from many mutable stack APIs, which generally return the dropped item. Consequently, `peek` becomes more important as the primary way to get an item from the top of the stack:\n\n```clj\n(peek m-stack)\n;=\u003e 3\n\n(pop m-stack)\n;=\u003e [1 2]\n\n(conj m-stack 4)\n;=\u003e [1 2 3 4]\n\n(+ (peek m-stack) (peek (pop m-stack)))\n;=\u003e 5\n```\n\n\u003e If you're using a collection (any implementor of `clojure.lang.IPersistentStack`) as a stack, it's idiomatic to use `conj` instead of `assoc`, `peek` instead of `last` and `pop` instead of `dissoc`. That avoids unnecessary confusion about how the collection is being used\n  \n\u003e Lists also implement `IPersistentStack`, but the functions there operate on the left side, i.e. beginning of the list\n\n### Using vectors instead of reverse\n\nWhen processing a list, it's pretty common to want to produce a new list in the same order. But if all you have is list, then you're left with backward list that needs to be reversed:\n\n```clj\n(defn m-map1 [f coll]\n  (loop [coll coll, acc nil]\n\t(if (empty? coll)\n\t  (reverse acc)\n\t  (recur (next coll) (cons (f (first coll)) acc)))))\n;=\u003e #'mbo/m-map1\n\n(m-map1 - (range 5))\n;=\u003e (0 -1 -2 -3 -4)\n```\n\nAfter the entire list has been walked once to produce the desired values, `reverse` walks it again to get them in the right order, which is inefficient and non-idiomatic.\nOne way to avoid `reverse` is to use a vector as the accumulator, instead of a list:\n\n```clj\n(defn m-map2 [f coll]\n  (loop [coll coll, acc []]\n\t(if (empty? coll)\n\t  acc\n\t  (recur (next coll) (conj acc (f (first coll)))))))\n;=\u003e #'mbo/m-map2\n\n(m-map2 - (range 5))\n;=\u003e [0 -1 -2 -3 -4]\n```\n\n### Subvectors\n\nProvide a fast way to take a slice of an existing vector based on start and end indices.\nTo produce a subvector we use the `subvec` function:\n\n```clj\n(subvec a-to-e 2 4)\n;=\u003e [\\C \\D]\n\n;;first index is inclusive, but the second is exclusive\n```\n\n\u003e There's a special logic for taking a `subvec` of a `subvec`, in which case the newest subvector keeps a reference to the original vector, not the intermediate subvector, which keeps both the creation and use of sub-subvectors fast and efficient.\n\n### Vectors as MapEntries\n\nClojure's hash map, just like hash tables and dictionaries in many other languages, has a mechanism to iterate through the entire collection. Clojure's solution for this iterator is, you guessed it - `seq`.  \nEach item in this seq needs to include both the key and the value, hence they are wrapped in a `MapEntry`. When printed, each entry looks like a vector:\n\n```clj\n(first {:width 10 :height 20 :depth 15})\n;=\u003e [:depth 15]\n\n;;not only does it look like a vector, it really is one:\n(vector? (first {:width 10 :height 20 :depth 15}))\n;=\u003e true\n\n;;which means you can use all the regular vector functions on it\n;;it even supports destructuring*\n```\n\n[destructuring?](#destructuring)\n\n```clj\n;;e.g. the following locals, 'dimension' and 'amount', will take on the value of each\n;;key/value pair in turn:\n(doseq [[dimension amount] {:width 10, :height 20, :depth 15}]\n  (println (str (name dimension) \":\") amount \" inches\"))\n;=\u003e depth: 15  inches\n;=\u003e width: 10  inches\n;=\u003e height: 20  inches\n;=\u003e nil\n\n(doc doseq)\n;=\u003e -------------------------\n;=\u003e clojure.core/doseq\n;=\u003e ([seq-exprs \u0026 body])\n;=\u003e Macro\n;=\u003e   Repeatedly executes body (presumably for side-effects) with\n;=\u003e   bindings and filtering as provided by \"for\".  Does not retain\n;=\u003e   the head of the sequence. Returns nil.\n```\n\nA `MapEntry` is its own type and has two functions for retrieving its contents, `key` and `val`, which do exactly the same thing as `(nth m-map 0)` and `(nth m-map 1)`.\n\n### What vectors aren't?\n\nVectors are versatile, but there are some useful patterns where they might seem like a good fit, but in fact the aren't.\n\n**Vectors aren't sparse**\n\nIf you have a vector of length _n_, the only position where you can insert a value is at index _n_, appending to the far right end. You can't skip some indices and insert at a higher index number (use hash map or sorted map).  \nAlthough you can replace values within a vector, you can't insert or delete items such that indices are adjusted (use finger trees for that).\n\n**Vectors aren't queues**\n\nUse a [PersistentQueue](#persistentqueue) for that.\n\n**Vectors aren't sets**\n\nIf you want to find out whether a vector contains a particular value, you might be tempted to use the `contains?` function, but that function checks whether a specific _key_, not _value_ is in a collection, which is really not useful for a vector.\n\n\u003e Vectors are probably the most frequently used collection type in Clojure. They are used as literals for argument lists and `let` bindings, for holding large amounts of application data and as stacks and map entries\n  \n\u003e In almost all contexts, you can consider vectors, lists, and other sequences as interchangeable. They only differ in their performance characteristics, and in a few data-structure-specific operations.\n\n## Sets\n\nSet is a collection of unordered, unique elements.\n\nSets are surrounded by `#{...}`:\n\n```clj\n#{1 2 3}\n;=\u003e #{1 2 3}\n\n(#{:a :b :c :d} :c)\n;=\u003e :c\n\n(#{:a :b :c :d} :e)\n;=\u003e nil\n```\n\nIf you look at the previous two expressions, you'll see that the sets are in fact functions of their elements that return the matched element or `nil` if the element is not present (take a pause and read that a couple more times, examining the examples).\n\nElements can be accessed via the `get` function, which returns the queried value if it exists, or `nil` if it doesn't:\n\n```clj\n(get #{:a 1 2 :b} :b)\n;=\u003e :b\n\n(get #{:a 1 2 :b} :k)\n;=\u003e nil\n```\n\n**Searching a sequence for any of multiple items using a set and `some`**\n\nThe `some` function takes a predicate and a sequence. It applies the predicate to each element in turn, returning the first _truthy_ value returned by the predicate or else `nil`:\n\n```clj\n(some #{:b} [:a 1 :b 2])\n;=\u003e :b\n\n(some #{1 :b} [:a 1 :b 2])\n;=\u003e 1\n```\n\nUsing a set as the predicate supplied to `some` allows you to check whether any of the truthy values in the set are contained within the given sequence. This is a frequently used Clojure idiom for searching for containment within a sequence.\n\nThe key to understanding how sets determine whether an element is discrete lies in one simple statement: Given two elements, evaluating as equal, a set will contain only one, independent of concrete types:\n\n```clj\n(let s #{[1 2] (1 2)})  ;vector and list with the same items are considered equal\n\n;=\u003e IllegalArgumentException Duplicate key: (1 2)\n;=\u003e clojure.lang.PersistentHashSet.createWithCheck (PersistentHashSet.java:68)\n```\n\n**Sorted sets**\n\nTo ask for elements in a sorted order:\n\n```clj\n(sort #{2 4 1})\n;=\u003e (1 2 4)\n```\n\nAs long as the arguments to the `sorted-set` function are mutually comparable, you'll receive a sorted set. Otherwise an exception is thrown:\n\n```clj\n(sorted-set :b :c :a)\n;=\u003e #{:a :b :c}\n\n(sorted-set [3 4] [1 2])\n;=\u003e #{[1 2] [3 4]}\n\n(sorted-set :b 2 :c)\n\n;=\u003e ClassCastException clojure.lang.Keyword cannot be cast to java.lang.Number\n;=\u003e clojure.lang.Util.compare (Util.java:152)\n```\n\nYou can use your own comparator with `sorted-set-by` function.\n\n**Containment**\n\n`contains?` checks for **existence of a key** in a collection:\n\n```clj\n(contains? #{1 2 3} 3)\n;=\u003e true\n```\n\nMany newcomers to Clojure expect `contains?` to behave the same as Java's `java.util.Collection#contains` method, but it doesn't:\n\n```clj\n(contains? [1 2 4 3] 4)\n;=\u003e false\n```\n\nSince `contains?` looks for existence of a key it shouldn't work with sets, but it does. That is due to the fact that sets are implemented as maps with the same element as the _key_ and _value_ with an additional check for containment before insertion.\n\n### `clojure.set` namespace\n\n`clojure.set/intersection` function works as you might expect. Given two sets, it returns a set of the common elements. Given _n_ sets, it'll incrementally return the intersection of resulting sets and the next set:\n\n```clj\n(clojure.set/intersection #{:a :b :c} #{:d :c :b})\n;=\u003e #{:b :c}\n\n(clojure.set/intersection #{:a :e :i :o :u}\n\t\t\t\t\t\t  #{:a :u :r}\n\t\t\t\t\t\t  #{:r :u :s})\n;=\u003e #{:u}\n```\n\n`clojure.set/union` works as expected.  \n`clojure.set/difference` \"removes\" all the elements from the first set that are also present in the second set (known as _relative complement_).\n\n`conj` \"adds\" an element to the set:\n\n```clj\n(conj #{:a :b :c} :d)\n;=\u003e #{:a :c :b :d}\n```\n\n`disj` \"removes\" an element:\n\n```clj\n(disj #{1 2} 2)\n;=\u003e #{1}\n```\n\nYou can make a set out of any other collection with `set`:\n\n```clj\n(set [2 5 1])\n;=\u003e #{1 2 5}\n```\n\n## Maps\n\nMap is an unsorted, associative _key/value_ structure (associates keys with values).\nMaps are represented with curly braces `{...}` filled by alternating _key/value_ pairs, with or without commas:\n\n```clj\n{:name \"luka\", :weight 3 :color \"white\"}   ;notice missing comma\n;=\u003e {:weight 3, :name \"luka\", :color \"white\"}\n```\n\nWe can look up the _value_ by _key_ with `get`:\n\n```clj\n(get {\"cat\" \"meow\", \"dog\" \"woof\"} \"cat\")\n;=\u003e \"meow\"\n```\n\n`get` can also take a default value to return instead of `nil`, if the key doesn’t exist:\n\n```clj\n(get {:k :v} :w :default)\n;=\u003e :default\n```\n\nMaps can be used as verbs, directly:\n\n```clj\n({\"a\" 12, \"b\" 24} \"b\")  ;maps are functions of their keys\n;=\u003e 24\n```\n\nKeywords can also be used as verbs, which look themselves up:\n\n```clj\n(:raccoon {:weasel \"queen\", :raccoon \"king\"})\n;=\u003e \"king\"\n```\n\nIn addition to literal syntax, hash maps can be created with the `hash-map` function:\n\n```clj\n(hash-map :a 1, :b 2, :c 3, :d 4, :e 5)\n;=\u003e {:a 1, :c 3, :b 2, :d 4, :e 5}\n```\n\nMaps support heterogeneous keys, which means that keys can be of any type and each key can be of a different type:\n\n```clj\n(let [m {:a 1, 1 :b, [1 2 3] \"4 5 6\"}]\n  [(get m :a) (get m [1 2 3])])\n;=\u003e [1 \"4 5 6\"]\n\n;;which can also be written without 'get', using map as a function of its keys:\n(let [m {:a 1, 1 :b, [1 2 3] \"4 5 6\"}]\n  [(m :a) (m [1 2 3])])\n;=\u003e [1 \"4 5 6\"]\n```\n\nProviding a map to a `seq` function returns a sequence of map entries:\n\n```clj\n(seq {:a 1, :b 2})\n;=\u003e ([:a 1] [:b 2])   ;returns key/value pairs contained in vectors\n```\n\nA new hash map can be created idiomatically using `into`:\n\n```clj\n(into {} [[:a 1] [:b 2]])\n;=\u003e {:a 1, :b 2}\n\n;;even if pairs aren't vectors, they can easily be made to be\n;;here, the map function, that has nothing to do with map-the-data-structure,\n;;applies 'vec' to all the elements:\n(into {} (map vec '[(:a 1) (:b 2)]))\n;=\u003e {:a 1, :b 2}\n```\n\nIf the key/value pairs are laid out in a sequence consecutively, your pairs don't even have to be explicitly grouped. You can use `apply` to create a hash map:\n\n```clj\n(apply hash-map [:a 1 :b 2])\n;=\u003e {:a 1, :b 2}\n```\n\nAnother idiomatic way to build a map is to use `zipmap` to \"zip\" together two sequences, the first of which contains keys and the second one values:\n\n```clj\n(zipmap [:a :b] [1 2])\n;=\u003e {:b 2, :a 1}\n```\n\n`assoc` \"adds\" an element to a map: \n\n```clj\n(assoc {:bolts 1088} :camshafts 3)\n;=\u003e {:camshafts 3, :bolts 1088}\n```\n\n`assoc` adds keys if they are not present, and replaces values if they are already there. If you associate a value onto `nil`, it creates a new map:\n\n```clj\n(assoc nil 5 2)\n;=\u003e {5 2}\n```\n\n`merge` yields a map containing all the elements of all given maps, preferring the values from later ones:\n\n```clj\n(merge {:a 1, :b 2} {:b 3, :c 4})\n;=\u003e {:c 4, :a 1, :b 3}\n```\n\nRemove map element with `dissoc`:\n\n```clj\n(dissoc {:a 1, :b 2, :c 4} :c)\n;=\u003e {:a 1, :b 2}\n```\n\n**Sorted maps**\n\nThe function `sorted-map` builds a map sorted by the comparison of its keys:\n\n```clj\n(sorted-map :b 1 :a 2 :c 0)\n;=\u003e {:a 2, :b 1, :c 0}\n```\n\nIf you need alternative key ordering, or ordering for keys that are not naturally comparable, use `sorted-map-by`, which allows you to provide a comparison function:\n\n```clj\n(sorted-map-by #(compare %1 %2) \"bac\" 9 \"abc\" 2)\n;=\u003e {\"abc\" 2, \"bac\" 9}\n\n;;Explanation:\n;; by doing this:\n#(compare %1 %2)   ;%1 stands for first parameter, in our case first map element\n\n;; we declared an anonymous function inline, which is the same as writing:\n(defn m-compare [first second]\n  (compare first second))\n\n;; and then passing that function to sorted-by-map:\n(sorted-map-by m-compare \"bac\" 9 \"abc\" 2)\n;=\u003e {\"abc\" 2, \"bac\" 9}\n```\n\nSorted maps (and sets) support efficient jump to a particular key and walk forward or backward from there through the collection. This is where `subseq` and `rsubseq` come in:\n\n```clj\n(def sm (sorted-map :a 1, :b 2, :c 3, :d 4, :e 5, :f 6, :g 7))\n\n(subseq sm \u003e :e)\n;=\u003e ([:f 6] [:g 7])\n\n(subseq sm \u003e :c \u003c :f)\n;=\u003e ([:d 4] [:e 5])\n```\n\nThere's one important difference in how sorted maps and sets handle numeric keys. A number can be represented by different types (`long`, `int`, `float`,...) and in a hash map, those types are preserved, while in a sorted map all those types are converted to the most precise one:\n\n```clj\n(assoc {1 :int} 1.0 :float)\n;=\u003e {1.0 :float, 1 :int}\n\n(assoc (sorted-map 1 :int) 1.0 :float)  ;only one is kept, since maps are unique\n;=\u003e {1 :float}\n```\n\nWhen we're adding an element to a sorted map (or set), Clojure uses equality to determine both, the sort order and key presence (remember, maps have unique keys).\n\n**Array maps**\n\nArray maps are used to guarantee that the order of insertions will be preserved (just like vectors and arrays do):\n\n```clj\n(hash-map :a 1, :b 2, :c 3)\n{:a 1, :c 3, :b 2}\n\n(array-map :a 1, :b 2, :c 3)\n{:a 1, :b 2, :c 3}\n```\n\n\u003e Like vectors, any item in a map literal is evaluated before the result is stored in the map. Unlike vectors, the order in which they are evaluated isn't guaranteed.\n\n## Persistence, immutability and functional programming\n\nWe'll start this section by giving a couple of phrases that encapsulate Clojure's immutability principles.\n\n\u003e if two objects aren't equal forever, then they're technically never equal\n\n\u003e there's a difference between a mutable object and a mutable reference. The default in Java is that there are references that may point to mutable data, but in Clojure, there are only mutable references\n\n\u003e immutable objects are always thread safe (Brian Goetz)\n\n**Structural sharing**\n\n```clojure\n(def baselist (list :barnabas :adam))\n\n(def lst1 (cons :willie baselist))\n\n(def lst2 (cons :phoenix baselist))\n\nbaselist\n;=\u003e (:barnabas :adam)                 ;baselist stays unchanged\n\nlst1\n;=\u003e (:willie :barnabas :adam)\n\nlst2\n;=\u003e (:phoenix :barnabas :adam)\n\n(= (next lst1) (next lst2))           ;they are not only equal\n;=\u003e true\n\n(identical? (next lst1) (next lst2))  ;but also the same underlying object\n;=\u003e true\n```\n\nYou can think of `baselist` as a common historical version of `lst1` and `lst2`, but it's also the shared part of both lists. Not only are the `next` parts of both lists equal, they are identical (the same instance in memory).\n\nUnlike lists, vectors and maps allow changes anywhere in the collection, not just on one end. This is made possible by the underlying data structure that those collection types are built upon - a tree.\n\nA tree allows interior changes and still maintains shared structure between different versions/changes.\n\nTo demonstrate how _structural sharing_ works, we'll build a simple tree, where each node will have three fields: a value, a left branch and a right branch:\n\n```clojure\n{:val 50, :L nil, :R nil}\n```\n\nOur empty tree will be represented by `nil` and the map above will represent that empty tree after a single node (with value `50`) has been added.\n\nLet's start slowly. To handle just this initial case of adding a single node to an empty tree, we'll write `xconj` function like this:\n\n```clj\n(defn xconj [t v]     ;add item with value 'v' to tree 't'\n  (cond\n    (nil? t) {:val v, :L nil, :R nil})) ;if t is nil this will be the first node (root)\n\n(xconj nil 50)\n;=\u003e {:val 50, :L nil, :R nil}\n```\n\nOK, that works, but let's not start sucking each others' dicks just yet (\u003csup\u003eTM\u003c/sup\u003eMr Wolf). We need to handle the case of adding an item to a non-empty tree.\n\nSo our tree doesn't even look like a tree yet:\n\n\u003cimg src=\"https://github.com/mbonaci/clojure/raw/master/resources/UnbalancedBinaryTree-01.png\" alt=\"{:val 50, :L nil, :R nil}\" title=\"Unbalanced binary tree with a single node\" width=\"222px\" style=\"margin-left: auto; display: block; margin-right: auto;\" /\u003e\n\n`:L` and `:R` are `nil`, so, for the sake of simplicity, we'll just make a rule that if an element does not point to some other element, it means it is `nil`. Presented this way, our tree looks like a piece of crap:\n\n\u003cimg src=\"https://github.com/mbonaci/clojure/raw/master/resources/UnbalancedBinaryTree-02.png\" alt=\"{:val 50, :L nil, :R nil}\" title=\"Unbalanced binary tree with a single node\" width=\"133px\" style=\"margin-left: auto; display: block; margin-right: auto;\" /\u003e\n\nWhen adding a node to a non-empty tree, in order to keep the tree sorted, we must follow a simple rule: _the value of any node in our tree must be greater than its left child and smaller or equal to its right child._  \n\nSo, in order to honor that rule, we need to compare the value being added first with the root, then with other nodes, down the tree, until we find the appropriate place for it.  \n\nLet's try adding a couple of elements. How would we add value `40` to our tree?\n\n\u003cimg src=\"https://github.com/mbonaci/clojure/raw/master/resources/UnbalancedBinaryTree-03.png\" alt=\"{:val 50, :L nil, :R nil}\" title=\"Unbalanced binary tree with a single node\" width=\"280px\" style=\"margin-left: auto; display: block; margin-right: auto;\" /\u003e\n\nNow that you saw this crucial image, take a look at the next one (let's keep our `nil`s a bit longer, it will be easier to reason about the algorithm):\n\n\u003cimg src=\"https://github.com/mbonaci/clojure/raw/master/resources/UnbalancedBinaryTree-04.png\" alt=\"{:val 50, :L nil, :R nil}\" title=\"Unbalanced binary tree with a single node\" width=\"133px\" style=\"margin-left: auto; display: block; margin-right: auto;\" /\u003e\n\nHow on earth did element `40` ended up there?\n\n\n```clj\n(defn xconj [t v]\n  (cond\n    (nil? t) {:val v, :L nil, :R nil}   ;does tree exist?\n    (\u003c v (:val t))              ;if v is smaller than the current item's value\n          {:val (:val t),       ;make new item whose value is the value of current item\n           :L (xconj (:L t) v), ;point :L to new tree by calling xconj on tree's :L child\n           :R (:R t)}           ;point :R to current item's :R\n    :else {:val (:val t)\n           :L (:L t)\n           :R (xconj (:R t) v)}\n   ))\n\n\n(defn xseq [t]\n  (when t\n    (concat (xseq (:L t)) [(:val t)] (xseq (:R t)))))\n\n;;what is 'cond'?\n(doc cond)\n;=\u003e -------------------------\n;=\u003e clojure.core/cond\n;=\u003e ([\u0026 clauses])\n;=\u003e Macro\n;=\u003e   Takes a set of test/expr pairs. It evaluates each test one at a\n;=\u003e   time.  If a test returns logical true, cond evaluates and returns\n;=\u003e   the value of the corresponding expr and doesn't evaluate any of the\n;=\u003e   other tests or exprs. (cond) returns nil.\n```\n\nThis is how our tree looks like:\n\n\u003cimg src=\"https://github.com/mbonaci/clojure/raw/master/resources/UnbalancedBinaryTree.png\" alt=\"Unbalanced binary tree\" title=\"Unbalanced binary tree\" width=\"300px\" style=\"margin-left: auto; display: block; margin-right: auto;\" /\u003e\n\nThis is how our tree would look like if it was balanced. Compare number of hops needed to find value `20`.\n\n\u003cimg src=\"https://github.com/mbonaci/clojure/raw/master/resources/BalancedBinaryTree.png\" alt=\"Balanced binary tree\" title=\"Balanced binary tree\" width=\"510px\" style=\"margin-left: auto; display: block; margin-right: auto;\" /\u003e\n\n\n\u003e persistent collections are immutable, in-memory (not on-disk) collections that allow you to preserve historical versions of their state.\n\nSince arrays are mutable, any changes happen in-place:\n\n```clj\n(def ds (into-array [:frane :luka :glupaca]))  ;mutable\n;=\u003e #'mbo/ds\n\n;; btw Glupaca is the name of our cat (which means something like \"stupid women\")\n\n(seq ds)     ;only for nice REPL printout\n;=\u003e (:frane :luka :glupaca)\n\n(aset ds 2 :suzi)   ;replace third element of the array\n;=\u003e :suzi\n\n(seq ds)\n;=\u003e (:frane :luka :suzi)\n```\n\nUsing one of Clojure's persistent data structures shows the difference:\n\n```clj\nmbo=\u003e (def ds [:frane :luka :suzi])  ;init persistent collection\n;=\u003e #'mbo/ds\n\nds            ;print ds to REPL\n;=\u003e [:frane :luka :suzi]\n\n(def ds8 (replace {:suzi :glupaca} ds))   ;replace third element and bind the\n;=\u003e #'mbo/ds8                             ;new collection to ds8\n\nds            ;ds did not change\n;=\u003e [:frane :luka :suzi]\n\nds8           ;the newly created collection\n;=\u003e [:frane :luka :glupaca]\n```\n\n# Symbols\n\nClosest thing to a variable in Clojure. Primarily used to provide a name for a given value, i.e. to refer to function parameters, local variables, globals, and Java classes.\n\nUnlike keywords, symbols are not unique based solely on their names:\n\n```clj\n(identical? 'node 'node)\n;=\u003e false\n\n;; identical? returns true only if symbols are the same object\n(let [x 'node y x] (identical? x y))\n;=\u003e true\n```\n\nEach `node` symbol is a discrete object that only happens to share a name. Though name is the basis for symbol equality:\n\n```clj\n(= 'node 'node)\n;=\u003e true\n\n(name 'node)\n;=\u003e \"node\"\n```\n\nWe can define a meaning for a symbol within a specific expression, using `let`.\nThe `let` expression first **takes a vector of bindings**: alternating symbols and values that those symbols are bound to within the remainder of the expression.  \n\n“Let the symbol `cats` be `5`, and construct a string composed of `\"I have \"`, `cats`, and `\" cats\"`:\n\n```clj\n(let [cats 5] (str \"I have \" cats \" cats.\"))\n;=\u003e \"I have 5 cats.\"\n```\n\nLet bindings, also called **locals**, apply only within the `let` expression itself. They also override any existing definitions for symbols at that point in the program. For example, we can redefine addition to mean subtraction, for the duration of a `let`:\n\n```clj\n(let [+ -] (+ 2 3))\n;=\u003e -1\n```\n\nThat definition does not apply outside the `let`:\n\n```clj\n(+ 2 3)\n;=\u003e 5\n```\n\nWe can also provide multiple bindings. Since Clojure doesn’t care about spacing, alignment, or newlines, we’ll write this on multiple lines, for clarity:\n\n```clj\n(let [person \"joseph\"\n      num-cats 186]\n  (str person \" has \" num-cats \" cats!\"))  ;the body\n;=\u003e \"joseph has 186 cats!\"\n```\n\nWhen multiple bindings are given, they are evaluated in order. Later bindings can use previous bindings:\n\n```clj\n(let [cats 3\n      legs (* 4 cats)]\n  (str legs \" legs all together\"))\n;=\u003e \"12 legs all together\"\n```\n\n\u003e a symbol whose name is prefixed with a namespace, followed by a slash, is called **fully qualified symbol**:\n\n```clj\nclojure.core/map\n;=\u003e #\u003ccore$map clojure.core$map@2a0406c4\u003e\n\nclojure.set/union\n;=\u003e #\u003cset$union clojure.set$union@1be2bcc8\u003e\n```\n\nThe body is sometimes described as an _implicit do_ (see [blocks bellow](#blocks)) because it follows the same rules: you may include any number of expressions and all will be evaluated, but only the value of the last one is returned.\n\nBecause they’re immutable, _locals_ can’t be used to accumulate results. Instead,\nyou'd use a high level function or loop/recur form.\n\nTo summarize, `let` defines the meaning of symbols within an expression. When Clojure evaluates a `let`, it replaces all occurrences of those symbols in the rest of the `let` expression with their corresponding values, then evaluates the rest of the expression.\n\n**Metadata**\n\nClojure allows the attachment of metadata to various objects, including symbols. `with-meta` function takes an object and a map and returns another object of the same type with the metadata attached:\n\n```clj\n(let [x (with-meta 'node {:js true})    ;attach :js to 'node and assign to x\n\t  y (with-meta 'node {:js false})]\n  [(= x y)            ;true because they both hold the same symbol, 'node\n   (identical? x y)   ;false because they are different instances\n   (meta x)\n   (meta y)])\n;=\u003e [true false {:js true} {:js false}]\n```\n\n**Symbols and namespaces**\n\nLike keywords, symbols don't belong to any specific namespace:\n\n```clj\nuser=\u003e (ns what-where)\n;=\u003e nil\n\nwhat-where=\u003e (def one-simbol 'where-is-it)\n;=\u003e #'what-where/one-simbol\n\nwhat-where=\u003e one-simbol\n;=\u003e where-is-it\n\nwhat-where=\u003e (resolve 'one-simbol)\n;=\u003e #'what-where/one-simbol  ;looks like namespace-qualified symbol\n                             ;but it's just a characteristic of symbol evaluation\n\nwhat-where=\u003e `one-symbol   ;back tick\n;=\u003e what-where/one-symbol\n```\n\n# Functions\n\nFunctions are a first-class type in Clojure. They can be used the same as any value (stored in Vars, held in collections, passed as arguments and returned as a result of other functions).\n\n```clj\n(let [x] (+ x 1))\n```\n\nWe can’t actually evaluate this program, because there’s no value for `x` yet. It could be `1`, or `4`, or `1453`. We say that `x` is _unbound_, because it has no binding to a particular value. This is the nature of the __function__: an expression with unbound symbols.\n\nFunction definition:\n\n```clj\n(fn [x] (+ x 1))\n;=\u003e #\u003cuser$eval1487$fn__1488 user$eval1487$fn__1488@6b7d28db\u003e\n```\n\nNamed function definition:\n\n```clj\n(let [twice (fn [x] (* 2 x))]\n   (+ (twice 1)\n   (twice 3)))\n;=\u003e 8\n```\n\n`let` bindings describe a similar relationship, but with a specific set of values for those arguments. `let` is evaluated immediately, whereas `fn` is evaluated later, when bindings are provided.\n\n## Vars\n\nOnce a `let` is defined, there’s no way to change it. If we want to redefine symbols for everyone, even code that we didn’t write, we need a new construct, a mutable variable.\n\n```clj\n(def cats 5)\n;=\u003e #'user/cats\n\n(type #'user/cats)\n;=\u003e clojure.lang.Var\n\ncats\n;=\u003e 5\n```\n\n`def` defines a type of value we haven’t seen before: a _Var_. _Vars_, like symbols, are references to other values. When evaluated, a _Var_ is replaced by its corresponding value.  \n\n`def` also binds the symbol `cats` (and its globally qualified equivalent `user/cats`) to that _Var_.  \n\nThe symbol `inc` points to the _Var_ `#'inc`, which in turn points to the function `#\u003ccore$inc clojure.core$inc@16bc0b3c\u003e`.  \n\nWe can see the intermediate Var with `resolve`:\n\n```clj\n'inc     ;symbol\n;=\u003e inc\n\n(resolve 'inc)\n;=\u003e #'clojure.core/inc    ;variable\n\n(eval 'inc)\n;=\u003e #\u003ccore$inc clojure.core$inc@d6206b5\u003e  ;value\n```\n\nWhy those two levels of indirection? Unlike with symbol, we can change the meaning of a Var for everyone, globally, at any time.  \n\nVars don't require a value. Instead we can just declare them and, by doing so, defer the binding of value.\n\n```clj\n(def y)\n;=\u003e #'user/y\n\n;; if we try to use it:\ny\n\n;=\u003e java.lang.IllegalStateException: Var user/y is unbound\n```\n\n## Named functions\n\n```clj\n(def half \n  (fn [number] (/ number 2)))\n;=\u003e #'user/half\n\n(half 8)\n;=\u003e 4\n```\n\nCreating a function and binding it to a variable is so common that it has its own form: `defn`, which is a _macro_ that is short for `def fn`:\n\n```clj\n(defn half [number] (/ number 2))\n;=\u003e #'user/half\n\n(half 8)\n;=\u003e 4\n```\n\nFunctions don’t have to take an argument. We’ve seen functions which take zero arguments, like `(+)`:\n\n```clj\n(defn half [] 1/2)\n;=\u003e #'user/half\n```\n\nBut if we try to use our earlier form with one argument, Clojure complains that the *arity* (the number of arguments to a function) is incorrect:\n\n```clj\n(half 8)\n\n;=\u003e ArityException Wrong number of args (1) passed to: user$half\n;=\u003e clojure.lang.AFn.throwArity (AFn.java:437)\n```\n\nTo handle multiple arities, functions have an alternate form, instead of an argument vector and a body, one provides a series of lists, each of which starts with an argument vector, followed by the body:\n\n```clj\n(defn half\n   ([] 1/2)\n   ([x] (/ x 2)))\n;=\u003e #'user/half\n\n(half)\n;=\u003e 1/2\n\n(half 8)\n;=\u003e 4\n```\n\nMultiple arguments work just like you expect. Just specify an argument vector of two, or three, or however many arguments the function takes.  \nSome functions can take any number of arguments. For that, Clojure provides `\u0026`, which slurps up all remaining arguments as a list:\n\n```clj\n(defn vargs [x y \u0026 more-args]\n   {:x x\n\t:y y\n\t:more more-args})\n;=\u003e #'user/vargs\n\n(vargs 1 2)\n;=\u003e {:x 1, :y 2, :more nil}\n\n(vargs 1 2 3 4 5)\n;=\u003e {:x 1, :y 2, :more (3 4 5)}\n```\n\n`x` and `y` are mandatory, though there don’t have to be any remaining arguments.  \n\nTo keep track of what arguments a function takes, why the function exists, and what it does, we usually include a **docstring**. Docstrings help fill in the missing context around functions, to explain their assumptions, context, and purpose to the world:\n\n```clj\n(defn launch\n   \"Launches a spacecraft into the given orbit by initiating a\n\tcontrolled on-axis burn. Does not automatically stage, but\n\tdoes vector thrust, if the craft supports it.\"\n   [craft target-orbit]\n   \"OK, we don't know how to control spacecraft yet.\")\n;=\u003e #'user/launch\n```\n\nDocstrings are used to automatically generate documentation for a Clojure programs, but you can also access them from the **REPL** (The `user=\u003e` prompt refers to the top-level namespace of the default REPL):\n\n```clj\n(doc launch)\n;=\u003e -------------------------\n;=\u003e user/launch\n;=\u003e ([craft target-orbit])\n;=\u003e   Launches a spacecraft into the given orbit by initiating a\n;=\u003e    controlled on-axis burn. Does not automatically stage, but\n;=\u003e    does vector thrust, if the craft supports it.\n;=\u003e nil\n```\n\n`doc` tells us the full name of the function, the arguments it accepts, and its docstring. This information comes from the `launch` Var’s metadata, and is saved there by `defn`. We can inspect metadata directly with the `meta` function:\n\n```clj\n(meta #'launch)\n;=\u003e {:arglists ([craft target-orbit]), :ns #\u003cNamespace user\u003e, :name launch, :column 1,\n;=\u003e :doc \"Launches a spacecraft into the given orbit by initiating a\\n   controlled \n;=\u003e on-axis burn. Does not automatically stage, but\\n   does vector thrust, if the \n;=\u003e craft supports it.\", :line 1, :file \"/tmp/form-init523009510157887861.clj\"}\n```\n\nThere’s some other juicy information in there, like the file the function was defined in and which line and column it started at, but that’s not particularly useful since we’re in the _REPL_, not a file. However, this does hint at a way to answer our motivating question: how does the `type` function work?\n\n## Blocks\n\nWhen you have a series or block of expressions that need to be treated as one, use `do`. All the expressions will be evaluated, but only the last one will be returned:\n\n```clj\n(do\n   6\n   (+ 5 4)\n   3)\n;=\u003e 3\n```\n\nThe expressions `6` and `(+ 5 4)` are perfectly legal. The addition in `(+ 5 4)` is even done, but the value is thrown away, only the final expression `3` is returned.\n\n## How does `type` work?\n\n`type`, like all functions, is a kind of object with its own unique type:\n\n```clj\ntype\n;=\u003e #\u003ccore$type clojure.core$type@2761df2a\u003e\n\n(type type)\n;=\u003e clojure.core$type\n```\n\nThis tells us that `type` is a particular instance, at memory address `39bda9b9`, of the type `clojure.core$type`. \n`clojure.core` is a namespace which defines the fundamentals of the Clojure language, and `$type` tells us that it’s named type in that namespace. None of this is particularly helpful, though. Maybe we can find out more about the `clojure.core$type` by asking what its supertypes are:\n\n```clj\n(supers (type type))\n;=\u003e #{java.io.Serializable java.lang.Runnable clojure.lang.AFunction \n;=\u003e clojure.lang.IMeta clojure.lang.AFn java.lang.Object clojure.lang.IObj \n;=\u003e java.util.Comparator clojure.lang.Fn java.util.concurrent.Callable \n;=\u003e clojure.lang.IFn}\n```\n\nThis is a set of all the types that include `type`. We say that `type` is an instance of `clojure.lang.AFunction`, or that it implements or extends `java.util.concurrent.Callable`, and so on. Since it’s a member of `clojure.lang.IMeta` it has metadata, and since it’s a member of `clojure.lang.AFn`, it’s a function. Just to double check, let’s confirm that `type` is indeed a function:\n\n```clj\n(fn? type)\n;=\u003e true\n```\n\n`type` can take a single argument, which it calls `x`. If it has `:type` metadata, that’s what it returns. Otherwise, it returns the class of `x`. Let’s take a deeper look at `type`’s metadata for more clues:\n\n```clj\n(doc type)\n;=\u003e -------------------------\n;=\u003e clojure.core/type\n;=\u003e ([x])\n;=\u003e   Returns the :type metadata of x, or its Class if none\n;=\u003e nil\n```\n\nThis function was first added to Clojure in version `1.0`, and is defined in the file `clojure/core.clj`, on line `3109`:\n\n```clj\n(meta #'type)\n;=\u003e {:ns #\u003cNamespace clojure.core\u003e, :name type, :arglists ([x]), :column 1, \n;=\u003e :added \"1.0\", :static true, :doc \"Returns the :type metadata of x, or its Class \n;=\u003e if none\", :line 3109, :file \"clojure/core.clj\"}\n```\n\nWe could go dig up the Clojure source code and read its definition there, or we could ask Clojure to do it for us. Aha! Here, at last, is how `type` works. It’s a function which takes a single argument `x`, and returns either `:type` from its metadata, or `(class x)`.\n\n```clj\n(source type)\n;=\u003e (defn type \n;=\u003e   \"Returns the :type metadata of x, or its Class if none\"\n;=\u003e   {:added \"1.0\"\n;=\u003e    :static true}\n;=\u003e   [x]\n;=\u003e   (or (get (meta x) :type) (class x)))\n;=\u003e nil\n```\n\n# Sequences\n\nA **sequential** collection is one that holds a series of values without reordering them.\n\nA **sequence** is a sequential collection that represents a series of values that may or may not exist yet (may have concrete values, may be lazy or empty). Few composite types are actually _sequences_, though several such as vectors are _sequential_. All an object needs to do to be a sequence is to support two core functions, `first` and `rest`\n\nA **seq** is a simple API for navigating collections which consists of two functions, `first` and `rest`\n\nIf two sequentials have the same values in the same order, `=` will return `true` for them, even if their concrete types are different:\n\n```clj\n(= [1 2 3] '(1 2 3))\n;=\u003e true\n```\n\nConversely, even if two collections have the same values in the same order, if one is a sequential collection and the other isn't, `=` will return `false`:\n\n```clj\n(= [1 2 3] #{1 2 3})\n;=\u003e false\n```\n\nIf the collection is empty, `seq` always returns `nil` and never an empty sequence (that goes for all other functions that return a `seq`, e.g. `next`).\n\n\u003e Clojure classifies each composite data type into 3 partitions: _sequentials_, _maps_ and _sets_. Everything that implements `java.util.List` is included in the sequential partition. Generally things that fall into other two partitions include set or map in their name\n\nEvery collection type provides at least one kind of `seq` object for walking through its elements\n\n## Recursion\n\n`cons`, makes a list beginning with the first argument, followed by all the elements in the second argument:\n\n```clj\n(cons 1 [2 3 4])\n;=\u003e (1 2 3 4)\n```\n\nProblem of incrementing all elements of a vector:\n\n```clj\n(defn inc-first [nums]\n   (if (first nums)\n\t ; If there's a first num, build a new list with cons\n\t (cons (inc (first nums))\n\t\t   (rest nums))\n\t ; If there's no first num, return an empty list\n\t (list)))\n;=\u003e #'user/inc-first\n\n(inc-first [])\n;=\u003e ()\n\n(inc-first [1 2 3])\n;=\u003e (2 2 3)\n```\n\nWhat if we called our function on `rest`?\n\n```clj\n(defn inc-all [nums]\n   (if (first nums)\n\t (cons (inc (first nums))\n\t\t   (inc-all (rest nums)))\n\t (list)))\n;=\u003e #'user/inc-all\n\n(inc-all [1 2 3 4])\n;=\u003e (2 3 4 5)\n```\n\nThis technique is called _recursion_, and it is a fundamental principle in working with collections, sequences, trees, graphs or any problem which has small parts linked together. There are two key elements in a recursive program:\n - Some part of the problem which has a known solution\n - A relationship which connects one part of the problem to the next\n\nIncrementing the elements of an empty list returns the empty list. This is our **base case**, the ground to build on. Our **inductive case**, also called the _recurrence relation_, is how we broke the problem up into incrementing the first number in the sequence, and incrementing all the numbers in the rest of the sequence. The `if` expression bound these two cases together into a single function, a function defined in terms of itself.\nLet’s parameterize our `inc-all` function to use any transformation of its elements:\n\n```clj\n(defn transform-all [f xs]\n   (if (first xs)\n\t (cons (f (first xs))\n\t\t   (transform-all f (rest xs)))\n\t (list)))\n;=\u003e #'user/transform-all\n\n(transform-all inc [1 2 3 4])\n;=\u003e (2 3 4 5)\n```\n\n## Loop\n\nWhen using recursion, you sometimes want to loop back not to the top of the function, but to somewhere inside the function body.  \nThe `loop` acts exactly like `let` but provides a target for `recur` to jump to:\n\n```clj\n(defn sum-down-from [initial-x]\n   (loop [sum 0, x initial-x]\n\t (if (pos? x)\n\t   (recur (+ sum x) (dec x))\n\t   sum)))\n;=\u003e #'user/sum-down-from\n```\n\nUpon entering the `loop`, the locals `sum` and `x` are initialized (like in `let`). A `recur` always loops back to the closest enclosing `loop` or `fn`. The `loop` locals are rebound to the values given in `recur`.  \n`recur` works only from the tail position.  \n\n`keyword` transforms a string to keyword:\n\n```clj\n(transform-all keyword [\"aa\" \"bb\" \"cc\"])\n;=\u003e (:aa :bb :cc)\n```\n\nTo wrap every element in a list:\n\n```clj\n(transform-all list [\"aa\" \"bb\" \"cc\"])\n;=\u003e ((\"aa\") (\"bb\") (\"cc\"))\n```\n\nWe basically implemented `map` function:\n\n```clj\n(map inc [1 2 3 4])\n;=\u003e (2 3 4 5)\n```\n\nThe function `map` relates one sequence to another. The type `map` relates keys to values. There is a deep symmetry between the two: maps are usually sparse, and the relationships between keys and values may be arbitrarily complex. The `map` function, on the other hand, usually expresses the same type of relationship, applied to a series of elements in a fixed order.\n\nClojure has a _special form_ called `recur` that's specifically used for tail recursion:\n\n```clj\n(defn print-down-from [x]\n   (when (pos? x)  ;return when x is no longer positive\n\t (println x)\n\t (recur (dec x))))\n;=\u003e #'user/print-down-from\n\n(print-down-from 5)\n;=\u003e 5\n;=\u003e 4\n;=\u003e 3\n;=\u003e 2\n;=\u003e 1\n;=\u003e nil\n```\n\n\u003e `when` is same as `if`, except it doesn't have the `else` part and it provides an implicit `do` in order to perform side-effects\n\nThis is nearly identical to how you’d structure a while loop in an imperative language. One significant difference is that the value of `x` isn’t decremented somewhere in the body of the loop. Instead, a new value is calculated as a parameter to `recur`, which immediately does two things: rebinds `x` to the new value and returns control to the top of `print-down-from`.  \nIf the function has multiple arguments, the `recur` call must as well, just as if you were calling the function by name instead of using the `recur` special form. And just as with a function call, the expressions in the `recur` are evaluated in order first and only then bound to the function arguments simultaneously.\n\n## Building Sequences\n\nWe can use recursion to expand a single value into a sequence of values, each related by some function. For instance (`pos?` returns `true` if `num` is greater than zero, else `false`):\n\n```clj\n(defn expand [f x count]\n   (if (pos? count)\n\t (cons x (expand f (f x) (dec count)))))\n;=\u003e #'user/expand\n\n(expand inc 0 10)\n;=\u003e (0 1 2 3 4 5 6 7 8 9)\n```\n\nOur base case is `x` itself, followed by the sequence beginning with `(f x)`. That sequence in turn expands to `(f (f x))`, and then to `(f (f (f x)))`, and so on. Each time we call `expand`, we count down by one using `dec`. Once the `count` is zero, `if` returns `nil`, and evaluation stops.\n\nClojure has a more general form of this function, called `iterate`:\n\n```clj\n(take 10 (iterate inc 0))\n;=\u003e (0 1 2 3 4 5 6 7 8 9)\n```\n\nSince this sequence is infinitely long, we’re using `take` to select only the first 10 elements. We can construct more complex sequences by using more complex functions:\n\n```clj\n(take 10 (iterate (fn [x] (if (odd? x) (+ 1 x) (/ x 2))) 10))\n;=\u003e (10 5 6 3 4 2 1 2 1 2)\n```\n\n`repeat` constructs a sequence where every element is the same:\n\n```clj\n(take 10 (repeat \"a\"))\n;=\u003e (\"a\" \"a\" \"a\" \"a\" \"a\" \"a\" \"a\" \"a\" \"a\" \"a\")\n\n(repeat 5 \"b\")\n;=\u003e (\"b\" \"b\" \"b\" \"b\" \"b\")\n```\n\n`repeatedly` simply calls a function `(f)` to generate an infinite sequence of values, over and over again, without any relationship between elements. For an infinite sequence of random numbers:\n\n```clj\n(rand)\n;=\u003e 0.6934524557647231\n\n(rand)\n;=\u003e 0.1355414232605504\n\n(take 3 (repeatedly rand))\n;=\u003e (0.18806021884865332 0.5231673860825672 0.38244349544358525)\n```\n\n`range` generates a sequence of numbers between two points. \n`(range n)` gives `n` successive integers starting at 0. \n`(range n m)` returns integers from `n` to `m-1`. \n`(range n m step)` returns integers from `n` to `m`, separated by `step`:\n\n```clj\n(range 5)\n;=\u003e (0 1 2 3 4)\n\n(range 5 8)\n;=\u003e (5 6 7)\n\n(range 5 25 5)\n;=\u003e (5 10 15 20)\n```\n\n`cycle` returns an infinite lazy sequence of repetitions of the items in a collection:\n\n```clj\n(take 6 (cycle (range 5 50 5)))\n;=\u003e (5 10 15 20 25 30)\n```\n\n## Transforming Sequences\n\n`map` applies a function to each element, but it has a few more tricks up its sleeve:\n\n```clj\n(map (fn [n vehicle] (str \"I've got \" n \" \" vehicle \"s\"))\n   [0 200 9]\n   [\"car\" \"train\" \"kiteboard\"])\n;=\u003e (\"I've got 0 cars\" \"I've got 200 trains\" \"I've got 9 kiteboards\")\n```\n\nIf given multiple sequences, `map` calls its function with one element from each sequence in turn. So the first value will be `(f 0 \"car\")`, the second `(f 200 \"train\")`, and so on. Like a zipper, map folds together corresponding elements from multiple collections. To sum three vectors, column-wise:\n\n```clj\n(map + [1 2 3]\n\t\t[4 5 6]\n\t\t[3 2 1])\n;=\u003e (8 9 10)\n```\n\nIf one sequence is bigger than another, `map` stops at the end of the smaller one. We can exploit this to combine finite and infinite sequences. For example, to number the elements in a vector:\n\n```clj\n(map (fn [index element] (str index \". \" element))\n\t  (iterate inc 0)\n\t  [\"erlang\" \"scala\" \"haskell\"])\n;=\u003e (\"0. erlang\" \"1. scala\" \"2. haskell\")\n```\n\nTransforming elements together with their indices is so common that Clojure has a special function for it: `map-indexed`:\n\n```clj\n(map-indexed (fn [index element] (str index \". \" element))\n\t\t\t  [\"erlang\" \"scala\" \"haskell\"])\n;=\u003e (\"0. erlang\" \"1. scala\" \"2. haskell\")\n```\n\nYou can also tack one sequence onto the end of another, like so:\n\n```clj\n(concat [1 2 3] [:a :b :c] [4 5 6])\n;=\u003e (1 2 3 :a :b :c 4 5 6)\n```\n\nAnother way to combine two sequences is to riffle them together, using `interleave`:\n\n```clj\n(interleave [:a :b :c] [1 2 3])\n;=\u003e (:a 1 :b 2 :c 3)\n```\n\nAnd if you want to insert a specific element between each successive pair in a sequence, try `interpose`:\n\n```clj\n(interpose :and [1 2 3 4])\n;=\u003e (1 :and 2 :and 3 :and 4)\n```\n\nTo reverse a sequence, use ... you guessed it, `reverse`:\n\n```clj\n(reverse [1 2 3])\n;=\u003e (3 2 1)\n\n(reverse \"woolf\")\n;=\u003e (\\f \\l \\o \\o \\w)  ;not a string\n```\n\nStrings are sequences too! Each element of a string is a character, written `\\f`. You can rejoin those characters into a string with `apply str`:\n\n```clj\n(apply str (reverse \"woolf\"))\n;=\u003e \"floow\"\n```\n\n…and break strings up into sequences of chars with `seq`:\n\n```clj\n(seq \"sato\")\n;=\u003e (\\s \\a \\t \\o)\n```\n\nTo randomize the order of a sequence, use `shuffle`:\n\n```clj\n(shuffle [1 2 3 4 5])\n;=\u003e [4 3 5 1 2]\n\n(apply str (shuffle (seq \"abracadabra\")))\n;=\u003e \"raradbabaac\"\n```\n\n## Subsequences\n\n`take` selects the first `n` elements, `drop` removes the first `n` elements, `take-last` and `drop-last` operate on the last `n` elements:\n\n```clj\n(take 3 (range 10))\n;=\u003e (0 1 2)\n\n(drop 3 (range 10))\n;=\u003e (3 4 5 6 7 8 9)\n\n(take-last 3 (range 10))\n;=\u003e (7 8 9)\n\n(drop-last 3 (range 10))\n;=\u003e (0 1 2 3 4 5 6)\n```\n\n`take-while` and `drop-while` work just like `take` and `drop`, but use a function to decide when to stop:\n\n```clj\n(take-while pos? [3 2 1 0 -1 -2 10])\n;=\u003e (3 2 1)\n```\n\nIn general, one can cut a sequence in twain by using `split-at` with a particular index. There’s also `split-with`, which uses a function to decide when to cut:\n\n```clj\n(split-at 4 (range 10))\n;=\u003e [(0 1 2 3) (4 5 6 7 8 9)]\n\n(split-with number? [1 2 3 :mark 4 5 6 :mark 7])\n;=\u003e [(1 2 3) (:mark 4 5 6 :mark 7)]\n```\n\nNotice that because indexes start at zero, sequence functions tend to have predictable number of elements.`(split-at 4)` yields four elements in the first collection, and ensures the second collection begins at index four. `(range 10)` has ten elements, corresponding to the first ten indices in a sequence. `(range 3 5)` has two (as in `5 - 3 = 2`) elements. These choices simplify the definition of recursive functions as well.\nWe can select particular elements from a sequence by applying a function. To pull up all positive numbers in a list, use `filter`:\n\n```clj\n(filter pos? [1 5 -4 -7 3 0])\n;=\u003e (1 5 3)\n```\n\n`filter` looks at each element in turn, and includes it in the resulting sequence only if `(f element)` returns a _truthy_ value. Its complement is `remove`, which only includes those elements where `(f element)` is `false` or `nil`:\n\n```clj\n(remove string? [1 \"tur\" :apple])\n;=\u003e (1 :apple)\n```\n\nOne can group a sequence into chunks using `partition`, `partition-all`, or `partition-by`. For instance, one might group alternating values into pairs like this:\n\n```clj\n(partition 2 [:cats 5 :bats 27 :crocs 0])\n;=\u003e ((:cats 5) (:bats 27) (:crocs 0))\n```\n\nSeparate a series of numbers into negative and positive subsequences:\n\n```clj\n(partition-by neg? [1 2 3 2 1 -1 -2 -3 -2 -1 1 2])\n;=\u003e ((1 2 3 2 1) (-1 -2 -3 -2 -1) (1 2))\n```\n\n`partition-all n collection` may include partitions with fewer than `n` items at the end:\n\n```clj\n(partition-all 3 [1 2 -5 3 2 1 -1 -2 -3 -2 -1 1 2])\n;=\u003e ((1 2 -5) (3 2 1) (-1 -2 -3) (-2 -1 1) (2))\n```\n\nwhile `partition` may not:\n\n```clj\n(partition 3 [1 2 -5 3 2 1 -1 -2 -3 -2 -1 1 2])\n;=\u003e ((1 2 -5) (3 2 1) (-1 -2 -3) (-2 -1 1))\n```\n\n### Collapsing subsequences\n\nAfter transforming a sequence, we often want to collapse it in some way, in order to derive some smaller value. For instance, we might want the number of times each element appears in a sequence:\n\n```clj\n(frequencies [:meow :mrrrow :meow :meow])\n;=\u003e {:meow 3, :mrrrow 1}\n```\n\nTo group elements by some function:\n\n```clj\n(pprint (group-by :first [{:first \"Li\"    :last \"Zhou\"}\n\t\t\t\t\t\t   {:first \"Sarah\" :last \"Lee\"}\n\t\t\t\t\t\t   {:first \"Sarah\" :last \"Dunn\"}\n\t\t\t\t\t\t   {:first \"Li\"    :last \"O'Toole\"}]))\n;=\u003e {\"Li\" [{:last \"Zhou\", :first \"Li\"} {:last \"O'Toole\", :first \"Li\"}],\n;=\u003e  \"Sarah\" [{:last \"Lee\", :first \"Sarah\"} {:last \"Dunn\", :first \"Sarah\"}]}\n```\n\nHere we’ve taken a sequence of people with first and last names, and used the `:first` keyword (which can act as a function!) to look up those first names. `group-by` used that function to produce a map of first names to lists of people, kind of like an index.\nIn general, we want to combine elements together in some way, using a function. Where `map` treated each element independently, reducing a sequence requires that we bring some information along. The most general way to collapse a sequence is `reduce`:\n\n```clj\n(doc reduce)\n;=\u003e -------------------------\n;=\u003e clojure.core/reduce\n;=\u003e ([f coll] [f val coll])\n;=\u003e   f should be a function of 2 arguments. If val is not supplied,\n;=\u003e   returns the result of applying f to the first 2 items in coll, then\n;=\u003e   applying f to that result and the 3rd item, etc. If coll contains no\n;=\u003e   items, f must accept no arguments as well, and reduce returns the\n;=\u003e   result of calling f with no arguments.  If coll has only 1 item, it\n;=\u003e   is returned and f is not called.  If val is supplied, returns the\n;=\u003e   result of applying f to val and the first item in coll, then\n;=\u003e   applying f to that result and the 2nd item, etc. If coll contains no\n;=\u003e   items, returns val and f is not called.\n\n(reduce + [1 2 3 4])\n;=\u003e 10\n\n(reduce + 1 [1 2 3 4])\n;=\u003e 11\n```\n\nTo see the reducing process in action, we can use `reductions`, which returns a sequence of all the intermediate states:\n\n```clj\n(reductions + [1 2 3 4])\n;=\u003e (1 3 6 10)\n```\n\nOftentimes we include a default state to start with. For instance, we could start with an empty set, and add each element to it as we go along:\n\n```clj\n(reduce conj #{} [:a :b :b :b :a :c])\n;=\u003e #{:a :c :b}\n```\n\nReducing elements into a collection has its own name: `into`. We can `conj [key value]` vectors into a map, for instance, or build up a list:\n\n```clj\n(into {} [[:a 2] [:b 3]])\n;=\u003e {:a 2, :b 3}\n\n(into (list) [1 2 3 4])\n;=\u003e (4 3 2 1)\n```\n\nBecause **elements added to a list appear at the beginning**, not the end, this expression **reverses the sequence**. Vectors `conj` onto the end, so to emit the elements in order, using reduce, we might try:\n\n```clj\n(reduce conj [] [1 2 3 4 5])\n;=\u003e [1 2 3 4 5]\n```\n\nRemember?\n\n```clj\n(conj [-1 0] [1 2 3 4 5])\n;=\u003e [-1 0 [1 2 3 4 5]]               ; not [-1 0 1 2 3 4 5]\n```\n\nThis looks like a `map` function. All that’s missing is some kind of transformation applied to each element:\n\n```clj\n(defn my-map [f coll]\n   (reduce (fn [output element]\n\t\t\t (conj output (f element)))\n\t\t   []\n\t\t   coll))\n;=\u003e #'user/my-map\n\n(my-map inc [1 2 3 4])\n;=\u003e [2 3 4 5]\n```\n\nSo `map` is just a special kind of `reduce`. What about, say, `take-while`?\n\n```clj\n(defn my-take-while [f coll]\n   (reduce (fn [out elem]\n\t\t\t (if (f elem)\n\t\t\t   (conj out elem)\n\t\t\t   (reduced out)))\n\t\t   []\n\t\t   coll))\n;=\u003e #'user/my-take-while\n```\n\nWe’re using a special function here, `reduced`, to indicate that we’ve completed our reduction early and can skip the rest of the sequence.\n\n```clj\n(my-take-while pos? [2 1 0 -1 0 1 2])\n;=\u003e [2 1]\n```\n\nMost of Clojure’s **sequence functions are lazy**. For instance, we can increment every number from zero to infinity:\n\n```clj\n(def infseq (map inc (iterate inc 0)))\n;=\u003e #'user/infseq\n\n(realized? infseq)\n;=\u003e false\n```\n\nThat function returned immediately. Because it hasn’t done any work yet, we say the sequence is unrealized. It doesn’t increment any numbers at all until we ask for them:\n\n```clj\n(take 10 infseq)\n;=\u003e (1 2 3 4 5 6 7 8 9 10)\n\n(realized? infseq)\n;=\u003e true\n```\n\n**Lazy sequences also remember their contents, once evaluated, for faster access.**\n\nFind the sum of the products of consecutive pairs of the first 1000 odd integers.\n\n```clj\n(reduce +\n\t\t (take 1000\n\t\t\t   (map (fn [pair] (* (first pair) (second pair)))\n\t\t\t\t\t(partition 2 1\n\t\t\t\t\t  (filter odd?\n\t\t\t\t\t\t(iterate inc 0))))))\n;=\u003e 1335333000\n```\n\n__Homework:__\n\n1. Write a function to find out if a string is a palindrome.\n\n```clj\n(defn palindrome? [word] \n  (== 0 (compare word (apply str (reverse word)))))\n```\n\n2. Find the number of `c`s in `“abracadabra”`.\n\n```clj\n(defn occurs-count [c word]\n  (get (frequencies (seq word)) c 0))\n```\n\n3. Write your own version of `filter`.\n\n```clj\n;=\u003e TBD\n```\n\n# Java interop\n\nClojure is _symbiotic_ with its host, providing its rich and powerful features, while Java provides an object model, libraries and runtime support.\n\nClojure strings are Java `String`s, numbers are `Number`s, collections implement `Collection`, fns implement `Callable` and `Runnable`, ...\n\nCore abstractions, such as `seq`, are Java interfaces (`ISeq`).  \nClojure `seq` library works on Java `Iterable`s, `String`s and arrays.  \nIt is possible to implement and extend Java interfaces and classes.  \n\n**Accessing static class members**\n\n... is trivial:\n\n```clj\njava.util.Locale/JAPAN\n;=\u003e #\u003cLocale ja_JP\u003e\n```\n\nIdiomatic Clojure prefers that you access static class members using a syntax like accessing a namespace-qualified Var:\n\n```clj\n(Math/sqrt 9)  ; the same as (java.lang.Math/sqrt 9)\n;=\u003e 3.0\n```\n\n**Creating Java class instances**\n\n```clj\n(new java.util.HashMap {\"foo\" 42 \"bar\" 8 \"baz\" \"beep boop\"})\n;=\u003e {\"baz\" \"beep boop\", \"foo\" 42, \"bar\" 8}\n\n;;idiomatic:\n(java.util.HashMap. {\"foo\" 42 \"bar\" 8 \"baz\" \"beep boop\"})   ;dot = constructor call\n;=\u003e {\"baz\" \"beep boop\", \"foo\" 42, \"bar\" 8}\n```\n\n**Accessing Java instance members with the dot operator**\n\nTo access instance properties, precede the property or method name with a dot:\n\n```clj\n(.x (java.awt.Point. 10 20))  ;create a new Point and access its member x\n;=\u003e 10\n```\n\nTo access instance methods, the dot form allows an additional argument to be passed to the method:\n\n```clj\n(.divide (java.math.BigDecimal. \"42\") 2K)\n;=\u003e 21M\n\n; what's this M for?\n(type 2M)\n;=\u003e java.math.BigDecimal\n```\n\n**Setting Java instance properties**\n\nIn the absence of mutator methods, in the form of `setX`, Java instance properties can be set using `set!` function:\n\n```clj\n(let [origin (java.awt.Point. 0 0)]\n  (set! (.x origin) 15)     ;(set! \u003cinstance_member_access\u003e \u003cvalue\u003e)\n  (str origin))\n;=\u003e \"java.awt.Point[x=15,y=0]\"\n```\n\n**The `..` macro**\n\nFor now, think of a macro as a convenience function. We'll meet them [later](#macros).  \nIn Java, it's a common practice to chain together a sequence of method calls, e.g:\n\n```java\nnew java.util.Date().toString().endsWith(\"2014\")  ;java\n```\n\n... which is equivalent to this Clojure expression:\n\n```clj\n(.endsWith (.toString (java.util.Date.)) \"2014\")\n;=\u003e true\n```\n\nWell, anyone would agree that this is rather difficult to read.  \nTo remedy this, Clojure provides us with `..` macro:\n\n```clj\n(.. (java.util.Date.) toString (endsWith \"2014\"))\n;=\u003e true\n```\n\n**The `doto` macro**\n\nIn Java, it's also common to initialize a fresh instance by calling a set of mutators:\n\n```java\njava.util.HashMap props = new java.util.HashMap();  /* java */\nprops.put(\"HOME\", \"/home/myself\");\nprops.put(\"SRC\",  \"src\");\nprops.put(\"BIN\",  \"classes\");\n```\n\nThat's obviously overly verbose, but it can be streamlined using the `doto` macro:\n\n```clj\n(doto (java.util.HashMap.)       ;do to HashMap all these things\n  (.put \"HOME\" \"/home/myself\")\n  (.put \"SRC\"  \"src\")\n  (.put \"BIN\"  \"classes\"))\n;=\u003e {\"HOME\" \"/home/myself\", \"BIN\" \"classes\", \"SRC\" \"src\"}\n```\n\n# Exceptions\n\nLike Java, Clojure also provides `try`, `catch`, `finally` and `throw` forms:\n\n```clj\n(throw (Exception. \"Thrown\"))\n\n;=\u003e Exception Thrown  user/eval1201 (form-init8547084957850583270.clj:1)\n\n(defn throw-catch [f]\n  [(try\n\t(f)\n\t(catch ArithmeticException e \"You did not? Not by zero! Noooooooooooo...\")\n\t(catch Exception e (str \"You blew it \" (.getMessage e)))\n\t(finally (println \"returning... \")))])\n;=\u003e #'user/throw-catch\n\n(throw-catch #(/ 10 5))\n;=\u003e returning... \n;=\u003e [2]\n\n(throw-catch #(/ 10 0))\n;=\u003e returning... \n;=\u003e [\"You did not? Not by zero! Noooooooooooo...\"]\n\n(throw-catch #(throw (Exception. \"dawg!\")))\n;=\u003e returning... \n;=\u003e [\"You blew it dawg!\"]\n```\n\n\u003e Clojure doesn't adhere to checked exception requirements, like Java does.\n\n\u003e When an exception is thrown in REPL, the result is stored in a Var named `*e`, which allows you to get more detail about the expression, such as the stack trace:\n\n```clj\n(.printStackTrace *e)\n```\n\n# Namespaces\n\nProvide a way to bundle related functions, macros and values.\n\n**Creating namespaces using `ns` macro**\n\n```clj\n(ns mbo.core.strings)\n;=\u003e nil\n;=\u003e mbo.core.strings=\u003e    ;from now on, this is our REPL prompt\n```\n\nThere's also a _Var_ `*ns*`, which holds the value of the current namespace.  \nWe know from before that any _Var_ created will be a member of the current namespace.\n\n```clj\nmbo.core.strings=\u003e (defn report-ns [] (str \"The current namespace is \" *ns*))\n;=\u003e #'mbo.core.strings/report-ns\n\nmbo.core.strings=\u003e (report-ns)\n;=\u003e \"The current namespace is mbo.core.strings\"\n\nmbo.core.strings=\u003e (defn sing [] (println \"Marjane Marjane, Marjane Marjane, ...\"))\n;=\u003e #'mbo.core.strings/sing\n\nmbo.core.strings=\u003e sing    ;Clojure looks it up in the current namespace\n;=\u003e #\u003cstrings$sing mbo.core.strings$sing@3987b05\u003e\n\nmbo.core.strings=\u003e (ns mbo.core.compat)   ;create another namespace\n;=\u003e nil\n\nmbo.core.compat=\u003e (report-ns)             ;try invoking function from another ns\n\nmbo.core.compat=\u003e CompilerException java.lang.RuntimeException: \n;=\u003e Unable to resolve symbol: report-ns in this context, \n;=\u003e compiling:(/tmp/form-init8547084957850583270.clj:1:1)\n\nmbo.core.compat=\u003e (mbo.core.strings/report-ns) ;fully qualified name works as expected\n;=\u003e \"The current namespace is mbo.core.compat\"\n```\n\n\u003e referring to a namespace symbol using fully qualified name will only work for namespaces created locally or those previously loaded. Read on, it'll become clear...\n\n**Using `:require` directive to load other namespaces**\n\n```clj\nmbo.core.compat=\u003e (ns mbo.core.set\n\t\t\t\t\t(:require clojure.set))\n;=\u003e nil\n;=\u003e mbo.core.set=\u003e  ;changed to new ns\n\nmbo.core.set=\u003e (clojure.set/intersection #{1 2 3} #{2 3 4})\n;=\u003e #{2 3}\n\nmbo.core.set=\u003e (intersection #{1 2 3} #{2 3 4})  ;invoke a clojure.set function directly\n\n;=\u003e CompilerException java.lang.RuntimeException: Unable to resolve symbol: \n;=\u003e intersection in this context, compiling:(/tmp/form-init8547084957850583270.clj:1:1)\n```\n\nThis construct indicates that we want the `clojure.set` namespace loaded, but we don't want the mappings of that namespace's symbols to `mbo.core.set` functions.\n\nWe can also use `:as` directive to create an additional alias to `clojure.set`:\n\n```clj\nmbo.core.set=\u003e (ns mbo.core.set-alias\n\t\t\t\t\t#_=\u003e   (:require [clojure.set :as s]))\n;=\u003e nil\n\nmbo.core.set-alias=\u003e (s/intersection #{1 2 3} #{2 3 4})\n;=\u003e #{2 3}\n```\n\nThe qualified namespace form (e.g. `clojure.set`) looks the same as a call to a _static class method_. The difference is that a _namespace symbol_ can only be used as a qualifier, whereas a _class symbol_ can also be referenced independently:\n\n```clj\nmbo.core.set-alias=\u003e clojure.set\n\n;=\u003e mbo.core.set-alias=\u003e CompilerException java.lang.ClassNotFoundException: \n;=\u003e clojure.set, compiling:(/tmp/form-init8547084957850583270.clj:1:691) \n\nmbo.core.set-alias=\u003e java.lang.Object\n;=\u003e java.lang.Object\n```\n\n\u003e That vagaries of namespace mappings from symbols to _Vars_, both qualified and unqualified, have the potential for confusion between _class names_ and _static methods_. In the beginning, that is. The differences will begin to feel natural as we progress (at least that's what _The joy of Clojure_ book promises :)\n\u003e One of the Clojure idioms is to use `my.Class` and `my.ns` for naming classes and namespaces, to help eliminate potential confusion.\n\n**Loading and creating mappings with `:use`**\n\n`:use`, unlike `:require`, maps Vars in another namespace to names in your own. That is typically used to avoid calling each function or macro with the qualifying namespace symbol:\n\n```clj\nmbo.core.set-alias=\u003e (ns mbo.test\n\t\t\t\t#_=\u003e   (:use [clojure.string :only [capitalize]]))\n;=\u003e nil\n\nmbo.test=\u003e (map capitalize [\"one\" \"two\"])\n;=\u003e (\"One\" \"Two\")\n;=\u003e mbo.test=\u003e\n```\n\n`:only` is used to indicate that only the listed functions should be mapped in the new namespace (good practice). The `:exclude` directive does the opposite.  \n`:use`, besides creating mappings, implicitly invokes `:require`.\n\n\u003e the idiomatic strategy for avoiding conflicts is to use `:require` with `:as` to create a namespace alias\n\n**Create mappings with `:refer`**\n\n`:refer` is a directive that works almost exactly like `:use`, except that it only creates mappings for libraries that have already been loaded (by being previously defined, by being one of Clojure's core namespaces or by having been explicitly loaded using `:require`).\n\n**Loading Java classes with `:import`**\n\n```clj\nmbo.test=\u003e (ns mbo.java\n\t  #_=\u003e   (:import [java.util HashMap]\n\t  #_=\u003e            [java.util.concurrent.atomic.AtomicLong]))\n;=\u003e nil\n\nmbo.java=\u003e (HashMap. {\"happy?\" true})\n;=\u003e {\"happy?\" true}\n```\n\n\u003e Any classes in the `java.lang` package are implicitly imported when namespaces are created\n\n**`nil` punning**\n\nSince, in Clojure, everything except `nil` and `false` is `true`, empty collections evaluate to `true` in boolean context. We need a way to test whether a collection is empty or not.  \n\nThis is where _nil punning_ comes in:\n\n```clj\n(seq [1 2 3])\n;=\u003e (1 2 3)\n\n(seq [])\n;=\u003e nil\n```\n\n`seq` function returns a sequence view of a collection or `nil` if the collection is empty.\n\n```clj\n(defn print-seq [s]\n  (when (seq s)\n\t(prn (first s))     ;prn prints each object in a newline (to the output stream)\n\t(recur (rest s))))\n\n(print-seq [1 2])\n;=\u003e 1\n;=\u003e 2\n;=\u003e nil\n```\n\nThe use of `seq` as a terminating condition is the idiomatic way of testing whether a sequence is empty\n\n# Destructuring\n\nAllows you to place a collection of names in a binding form where normally you'd put just a single name.  \n\n\u003e Destructuring is loosely related to _pattern matching_ (found in Haskell or [Scala](https://github.com/mbonaci/scala#case-classes-and-pattern-matching)), but much more limited in scope. For full-featured pattern matching in Clojure use [matchure](http://github.com/dcolthorp/matchure).\n\nPerhaps the simplest form of destructuring is picking apart a sequential thing (e.g. a vector or a list), giving each item a name:\n\n```clj\n(let [[fname mname lname] [\"Frane\" \"Luka\" \"Bonaci\"]]\n  (str lname \", \" fname \" \" mname))\n;=\u003e \"Bonaci, Frane Luka\"\n\n;; although this is syntactically correct, it isn't factually accurate\n;; my month and a half old twins are named Frane and Luka :)\n;; what can I say, my wife is a hero (that's what everybody's telling me these days)\n;; hmmm, I wonder why?\n```\n\nThis was a so called _positional destructuring_, which, as you might expect, doesn't work on maps and sets, because they are not logically aligned sequentially. But it does work on `java.util.regex.Matcher` and anything implementing `CharSequence` and `java.util.RandomAccess` interfaces.  \n  \n**Destructuring with a vector**\n  \nWe can also use an ampersand in a destructuring vector to indicate that any remaining values of the input should be collected into a (possibly lazy) `seq`:\n\n```clj\n(let [[a b c \u0026 more] (range 10)]\n  (println \"a b c are: \" a b c)\n  (println \"the rest is: \" more))\n;=\u003e a b c are:  0 1 2\n;=\u003e the rest is:  (3 4 5 6 7 8 9)\n```\n\nA useful feature of vector destructuring is `:as`, which is used to bind a local to the entire collection. It must be placed at the end, even after the `\u0026` local (if it exists):\n\n```clj\n(let [range-vec (vec (range 10))\n      [a b c \u0026 more :as all] range-vec]\n  (println \"a b c are: \" a b c)\n  (println \"the rest is \" more)\n  (println \"all is: \" all))\n;=\u003e a b c are:  0 1 2\n;=\u003e the rest is  (3 4 5 6 7 8 9)\n;=\u003e all is:  [0 1 2 3 4 5 6 7 8 9]\n```\n\n\u003e Notice the difference between `\u0026` and `:as`. While `:all` produces a vector, `\u0026` results with a `seq`.\n\n**Destructuring with a map**\n\n```clj\n(def full-name-map\n  {:fname \"Frane\" :mname \"Luka\" :lname \"Bonaci\"})\n\n(let [{fname :fname, mname :mname, lname :lname} full-name-map]\n  (str lname \", \" fname \" \" mname))\n;=\u003e \"Bonaci, Frane Luka\"\n```\n\nHere, the `:keys` feature might come in handy:\n\n```clj\n(let [{:keys [fname mname lname]} full-name-map]\n  (str lname \", \" fname \" \" mname))\n;=\u003e \"Bonaci, Frane Luka\"\n```\n\nBy using `:keys`, we're telling Clojure that the next form will be a vector of names that it should convert to keywords (e.g. `:fname`), in order to look \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmbonaci%2Fclojure","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmbonaci%2Fclojure","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmbonaci%2Fclojure/lists"}