In clojure, What is the best possible way to declare a global variable, the value of which needs to be changed in a function and this global variable need to be accessed in other namespaces
Ex:
(ns ..main
.....)
(def global_variable nil)
..
(defn main ...
Change the value of global variable here
)
Another name space
(ns accessvariable ...)
(println (main/global_variable))
What is the best way to do this?
Just store an atom in your global var:
(def global-var (atom nil))
Note: this is in response to the third comment on the question. dAni's answer applies to the question as asked.
Idiomatic Clojure favors functions whose outputs are determined only by their input parameters. This is in contrast to a function which relies on its parameters and global state, too. It is easy to convert a function which uses global data into one that does not - you just need to add a parameter that will contain the data. For example: instead of (defn print-global [] (println @global-atom-defined-elsewhere))
, you use (defn print-my-val [val] (println val))
.
If you use the command line argument extremely frequently, you might still find it more convenient to put the data in a global atom, instead of having everything use it as a parameter. This is up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With