2009-06-24 2 views
5

Что такое самый простой способ создать вектор различных ссылок?Clojure Vector of Refs

Использование (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 (несколько раз # (исх ноль)))) –

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>]