2009-06-24 42 views
5

Cách đơn giản nhất để tạo ra một vectơ các refs riêng biệt là gì?Clojure Vector tài liệu tham khảo

Sử dụng (repeat 5 (ref nil)) sẽ trả về một danh sách, nhưng tất cả họ sẽ tham khảo các ref giống nhau:

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

kết quả tương tự với (replicate 5 (ref nil)):

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

Trả lời

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

và sau đó quấn trong (vec (mất 5 (lặp đi lặp lại # (ref nil)))) –

4

Ok, điều này là khá thô, nhưng nó hoạt động:

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

Điều đó trả về LazySeq, vì vậy nếu bạn muốn/cần Vector, sau đó chỉ cần sử dụng:

user=> (vec (map (fn [_] (ref nil)) (range 5))) 
[#<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil> #<[email protected]: nil>] 
Các vấn đề liên quan