2009-06-24 14 views
5

Quel est le moyen le plus simple de créer un vecteur de refs distincts?Clojure Vecteur de Refs

L'utilisation (repeat 5 (ref nil)) retourne une liste, mais ils seront tous référence à la même ref:

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

Même résultat avec (replicate 5 (ref nil)):

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

Répondre

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

puis envelopper dans (VEC (prendre 5 (à plusieurs reprises # (réf nil)))) –

4

Ok, cela est assez brut, mais il fonctionne:

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

Cela renvoie un LazySeq, donc si vous voulez/avez besoin d'un Vector, alors utilisez simplement:

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