Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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
    
2  
@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

1 Answer 1

up vote 6 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

http://clojure.org/atoms

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
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. –  naiad Apr 6 '12 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 '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

 
discard

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.