tags:

views:

83

answers:

2

conj is used in (conj coll item), for example (conj #{} "Stu").

But, I found this example in 'Programming Clojure' book page16.

(alter visitors conj username)

I guess (conj visitors username) would be the correct usage. What's the secret?

+4  A: 

The "secret" is that alter is a special function that is called in a transaction on a ref, and it has the effect of inserting the current value of the ref as the first parameter to whichever function is supplied as its second argument.

In fact the normal usage for conj with a ref would be:

(conj @visitors username)

So alter roughly translates as follows:

(alter vistors conj username)
=> (ref-set visitors (conj @visitors username))
mikera
+1  A: 

It is not uncommon in Clojure for macros and higher order functions to take a function followed by args and then execute it by inserting a context-dependent argument before the supplied args. This makes caller's life a bit easier. This way you can write:

(alter visitors conj username)

instead of:

(alter visitors #(conj %1 username))

Some other forms that do this are: send,doto,update-in,->,alter-meta!.

Rafał Dowgird