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?

  • 2
    @RobertHarvey that's not quite the same thing
    – gtrak
    Apr 6, 2012 at 20:43
  • cycle is already a name for a core function, should pick something else
    – gtrak
    Apr 6, 2012 at 20:48
  • @gtrak: Oh! Right. Fixed.
    – amara
    Apr 6, 2012 at 20:50

1 Answer 1


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.

  • 1
    But... isn't atom a concurrency mechanism? I'm used to standard fields that are just a (fast, fast) memory location; this is confusing.
    – amara
    Apr 6, 2012 at 20:49
  • 4
    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: docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/…
    – gtrak
    Apr 6, 2012 at 20:52
  • 1
    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 = ...
    – amara
    Apr 7, 2012 at 0:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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