clojure

Functions

In Clojure, a function call is a list whose first element is a function

doc - shows documentation  (doc str)
find-doc - takes a regexp as a parameter and searches for documentation.
defn - defines a function.
def - defines a function or data.   (def <name> <some reference>)
ref - creates a reference.  (ref <some thing>)
alter - updates a reference. (alter r update-fn & args).  Needs a transaction.
dosync - creates a transaction.  example: (dosync (alter <reference_to_set> conj <new_value_for_set>))
str - function that concatenates a list into a string
conj - conjoin - builds a new collection with an additional item
deref - returns the value in the reference (abbreviated with @)
require - requires a clojure library
refer - once required, refer allows you to refer to code within a namspace without the fully qualified namespace.
use - combines require and refer (use :reload-all forces libraries to be reloaded).

Syntax for defn

(defn my-function
"This function does something extra special,
It makes things mine"
([] (my-function "stuff" ))  ;use list comprehension for each airity it accepts
([thing] (str "This is my " thing)))   ; use & collection-name to mop up extra airity, like *args in Ruby

Useful bits

*e ;A special variable that holds the last exception
(.printStackTrace *e)  ;uses the Java printStackTrace method to print the last exception's stack trace.
(load-file "temp.clj")  ; loads a file into the REPL.

To view the source of a function use the repl-utils

(use 'clojure.contrib.repl-utils)
(source identity)

Returns

(defn identity
  "Returns its argument."
  [x] x)

Common Parameter Names :preformattted: a - A Java array agt - An agent coll - A collection expr - An expression f - A function idx - Index r - A ref v - A vector val - A value

REPL

java -cp clojure.jar clojure.main

The REPL has very rudimentary editing. For a better experience, try running it via the JLine ConsoleRunner:

Forms

Reader Macros :paragraphs: Reader macros are abbreviations for longer list forms.

; - comment
' - prevent evaluation (quote)
# - anonymous function
@ - deref
^ - meta
#^ - metadata
#"[A-Za-z0-9]" - regexp
~ - unquote
~@ - unquote splicing
#' - var-quote

Links

blog comments powered by Disqus