2009-06-24 8 views
5

Qual è il modo più semplice per creare un vettore di riferimenti distinti?Clojure Vector of Refs

Utilizzando (repeat 5 (ref nil)) restituirà un elenco, ma saranno tutti riferimento allo stesso ref:

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

stesso risultato con (replicate 5 (ref nil)):

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

risposta

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

e poi avvolgere in (vec (prendere 5 (ripetutamente # (ref nil)))) –

4

Ok, questo è abbastanza grave, ma funziona:

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

Che restituisce un LazySeq, quindi se si desidera/ha bisogno di un Vettore, poi basta usare:

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