Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Simple example:

(def ticks 0)
(defn run-iteration []
  (def ticks (inc ticks)))

Though the usual case involves things that don't change more than once every several hundred ms.

How to do this idiomatically?

Edit: and why is the idiomatic way idiomatic, and why is it good?

share|improve this question
@RobertHarvey that's not quite the same thing – gtrak Apr 6 '12 at 20:43
cycle is already a name for a core function, should pick something else – gtrak Apr 6 '12 at 20:48
@gtrak: Oh! Right. Fixed. – naiad Apr 6 '12 at 20:50
up vote 8 down vote accepted

What you really want is one of clojure's mutable reference types, for your example, I would use an atom, like this:

(def ticks (atom 0))
(defn ++ticks []
  (swap! ticks inc))

and to get the value, @ticks

Don't use a def for this, in fact the only sane reasons you can redef is to enable development at the repl or hot code reloading.

The above solution is idiomatic as clojure has a philosophy of maximal immutability and controlled mutability. An atom is the simplest form of controlled mutability provided by clojure. This solution is ready for use by multiple threads, and is appropriate for use by a single thread, without you having to think about it too much. That's the clojure way.

share|improve this answer
But... isn't atom a concurrency mechanism? I'm used to standard fields that are just a (fast, fast) memory location; this is confusing. – naiad Apr 6 '12 at 20:49
fields also have concurrency semantics, an atom just has sane ones. An atom is plenty fast. It's just a wrapper over one of these:… – gtrak Apr 6 '12 at 20:52
oh! cool! For anyone reading who doesn't want to examine the sources, deref and reset! do little more than standard java fields; (with class Box {Object value;}) box.value and box.value = ... – naiad Apr 7 '12 at 0:54

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.