Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Clojure how to define a global variable which can be accessed from other name space

Tags:

clojure

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?

like image 337
gechu Avatar asked Jan 13 '16 19:01

gechu


2 Answers

Just store an atom in your global var:

(def global-var (atom nil))
like image 90
DanLebrero Avatar answered Sep 21 '22 16:09

DanLebrero


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.

like image 33
WolfeFan Avatar answered Sep 20 '22 16:09

WolfeFan