Collections 我有办法在Clojure中存储全局数据集合吗?

Collections 我有办法在Clojure中存储全局数据集合吗?,collections,clojure,global-variables,mutable,Collections,Clojure,Global Variables,Mutable,我需要在Clojure中全局存储一些数据的方法。但我找不到办法。我需要在运行时加载一些数据,并将其放入全局对象池中,以便以后使用它进行操作。应该在一些函数集中访问这个池,以便从中设置/获取数据,就像一个内存中的小数据库一样,使用类似散列的语法进行访问 我知道这在函数式编程中可能是一种糟糕的模式,但我不知道存储动态对象集以在运行时访问/修改/替换它的其他方法。HashMap是一种解决方案,但无法使用序列函数访问它,当我需要使用这种集合时,我错过了Clojure的灵活性。Lisps语法是一种很好的语

我需要在Clojure中全局存储一些数据的方法。但我找不到办法。我需要在运行时加载一些数据,并将其放入全局对象池中,以便以后使用它进行操作。应该在一些函数集中访问这个池,以便从中设置/获取数据,就像一个内存中的小数据库一样,使用类似散列的语法进行访问

我知道这在函数式编程中可能是一种糟糕的模式,但我不知道存储动态对象集以在运行时访问/修改/替换它的其他方法。HashMap是一种解决方案,但无法使用序列函数访问它,当我需要使用这种集合时,我错过了Clojure的灵活性。Lisps语法是一种很好的语法,但它在纯度上有点困难,即使开发人员在某些地方不需要它

这就是我想用的方法:

; Defined somewhere, in "engine.templates" namespace for example
(def collection (mutable-hash))

; Way to access it
(set! collection :template-1-id (slurp "/templates/template-1.tpl"))
(set! collection :template-2-id "template string")

; Use it somewhere
(defn render-template [template-id data]
  (if (nil? (get collection template-id)) "" (do-something))) 

; Work with it like with other collection
(defn find-template-by-type [type]
  (take-while #(= type (:type %)) collection)]
有人能帮我完成这样的任务吗?谢谢

看一看

您的示例可以适用于以下内容(未经测试):


交换是如何以线程安全的方式更新atom的值。另外,请注意,上面对集合的引用前面有@符号。这就是如何得到原子中包含的值。@符号是
(deref collection)

哇!看起来原子是按我需要的方式工作的。非常感谢你!作为旁注,
defonce
而不是
def
与全局变量和原子一起使用很有意思。谢谢,我也会看看这个功能!
; Defined somewhere, in "engine.templates" namespace for example
(def collection (atom {}))

; Way to access it
(swap! collection assoc :template-1-id (slurp "/templates/template-1.tpl"))
(swap! collection assoc :template-2-id "template string")

; Use it somewhere
(defn render-template [template-id data]
  (if (nil? (get @collection template-id)) "" (do-something))) 

; Work with it like with other collection
(defn find-template-by-type [type]
  (take-while #(= type (:type %)) @collection)]