Clojure Programming/Examples/Cookbook

How to do structural binding or destructuring in function argument lists or let bindings.
Instead of accessing values in a map like this:

You can destructure the map like this:

or better yet, like this:

Instead of accessing vector elements like this:

you can destructure the vector like this:

How to write x = x+ 1
Or, a more idiomatic way would be to use inc:

The most idiomatic way is not do this at all. Why would you want to do x=x+1 in clojure?

generate infinite sequence of nested function calls
The infinite sequence (0 1 2 3 4 5 ....) can be defined using (range) since clojure 1.2:

or alternatively using iterate:

Polymorphism
Overload function based on number of arguments:

Create multi-method which dispatches on the number of its arguments:

Create a multi-method which dispatches on the class of its arguments:

Create a multi-method that dispatches on the value of its argument:

Accessing inner classes
Class definition in Java.

Import Java Classes from Jar File
The first item in the import list is the package name followed by the names of all the classes in the package to import.

Note: you must use the package name and not the name of the jar file which contains the package of classes. If you're not sure what the package name is, from a terminal type:

Let's say you see something like: org/jfugue/Anticipator.class

Then the import statement would be:

Not:

Write to Output File
Writing creates a new file or will overwrite existing file

To append to existing file use "spit" with ":append" set to true

Now our file should say:

Strings
Use str to concatenate strings:

and use apply with str as an argument to concatenate a sequence of strings:

Use interpose to join a sequence of strings with a separator:

Use re-seq to split a string at boundaries by a regular expression, here \w+ denotes a character class of all alphanumeric characters plus "_":

Reversing a string is done via <tt>reverse</tt> which returns a sequence of the characters in the string; use <tt>apply</tt> with <tt>str</tt> to turn it into a string again:

and to convert any object into a string simply supply it as an argument to the <tt>str</tt> function: