On May 3, 2014, at 9:45 AM, Dave Tenny <[email protected]> wrote:
> I'm still struggling with how to write the most readable, simple clojure code
> to deal with dynamically bindings.
>
> What is the graceful clojure equivalent of common lisp special variables for
> the following scenario.
>
> If I were writing common lisp I'd just do something like (pardon if my lisp
> is rusty here):
>
> (defvar *x* 1)
> ... do stuff with *x* ...
> (setq *x* 2)
> ... do stuff with *x* ...
> (let ((*x* 3)) (do stuff with *x*...)
> ;; do stuff with *x* that's currently at 2
>
>
> The way I'm tempted to do this in clojure is
>
> (def ^{:dynamic true} *x* (atom 1))
> ... do stuff with @*x* ...
> (reset! *x* 2)
> ... do stuff with @*x* ...
> (binding [*x* (atom 3)] (do stuff with @*x*))
Inside the binding you can call set! if you must.
You can also just use 'def' to redefine the global binding. It says this:
"Using def to modify the root value of a var at other than the top level is
usually an indication that you are using the var as a mutable global, and is
considered bad style. Consider either using binding to provide a thread-local
value for the var, or putting a ref or agent in the var and using transactions
or actions for mutation." in the docs at http://clojure.org/special_forms#def
which is roughly what you did with the atom. But it'll work.
You can also just write it:
(def ^:dynamic *x* (atom 1))
which is a little less verbose.
Cheers,
Bob
>
>
> Is that the simplest way to map between the two language scenarios?
> Or is there something simpler, perhaps using some var-* apis or what have you?
>
>
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to [email protected]
> Note that posts from new members are moderated - please be patient with your
> first post.
> To unsubscribe from this group, send email to
> [email protected]
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
> ---
> You received this message because you are subscribed to the Google Groups
> "Clojure" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.