2009-06-24 73 views
5

什么是最简单的方法来创建一个不同的参考向量?Clojure向量的参考

使用(repeat 5 (ref nil))将返回一个列表,但他们都将参考同一个参考:

user=> (repeat 5 (ref nil)) 
(#<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<R 
[email protected]: nil>) 

同样的结果与(replicate 5 (ref nil))

user=> (replicate 5 (ref nil)) 
(#<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> 
#<[email protected]: nil>) 

回答

8
user> (doc repeatedly) 
------------------------- 
clojure.core/repeatedly 
([f]) 
    Takes a function of no args, presumably with side effects, and returns an infinite 
    lazy sequence of calls to it 
nil 

user> (take 5 (repeatedly #(ref nil))) 
(#<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil>) 
us 
+1

,然后包裹在(VEC(坐5(反复#(REF为零)))) – 2009-06-24 20:37:40

4

好吧,这是很严重,但它的工作原理:

user=> (map (fn [_] (ref nil)) (range 5)) 
(#<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil>) 

返回一个LazySeq,所以如果你想/需要一个向量,就用:

user=> (vec (map (fn [_] (ref nil)) (range 5))) 
[#<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil>]