Sha*_*ron 6 clojure clojurescript
我试图找到推迟var初始化的惯用方法(我真的打算成为不可变的).
(def foo nil)
...
(defn init []
; (def foo (some-function))
; (set! foo (some-function)))
Run Code Online (Sandbox Code Playgroud)
我知道Rich Hickey说重新定义不是惯用的.是set!
合适的吗?
我会用delay
:
采用一个表达式体并产生一个Delay对象,该对象仅在第一次强制(使用force或deref/@)时调用正文,并将缓存结果并在所有后续强制调用中返回它.另见 - 实现?
用法示例:
(def foo (delay (init-foo))) ;; init-foo is not called until foo is deref'ed
(defn do-something []
(let [f @foo] ;; init-foo is called the first time this line is executed,
;; and the result saved and re-used for each subsequent call.
...
))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
271 次 |
最近记录: |