chr*_*alz 1 clojure persistent transient
我正在学习Clojure,并在此过程中从O'Reilly的书"Clojure Programming"中看到了这个例子:
(let [tm (transient {})]
(doseq [x (range 100)]
(assoc! tm x 0))
(persistent! tm))
Run Code Online (Sandbox Code Playgroud)
它给出了结果{0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6 0, 7 0}.
也:
(let [tm (transient {})]
(assoc! tm 0 0)
(assoc! tm 1 0)
(assoc! tm 2 0)
(assoc! tm 3 0)
(assoc! tm 4 0)
(assoc! tm 5 0)
(assoc! tm 6 0)
(assoc! tm 7 0)
(assoc! tm 8 0)
(persistent! tm)
)
Run Code Online (Sandbox Code Playgroud)
给出相同的结果:{0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6 0, 7 0}.
为什么只有前八个项目才能成为持久集合?
A. *_*ebb 10
为什么只有前8项?
(type {})
;=> clojure.lang.PersistentArrayMap
(type {0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6, 0})
;=> clojure.lang.PersistentArrayMap
(type {0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6, 0, 7 0})
;=> clojure.lang.PersistentArrayMap
(type {0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6, 0, 7 0, 8 0})
;=> clojure.lang.PersistentHashMap
Run Code Online (Sandbox Code Playgroud)
因为地图的表示在8对和更少对之间变化到8对或更多对.由于你在原版上"抨击",你从未捕捉到代表性的变化.
使用瞬态时,必须始终捕获并使用返回值.