简体   繁体   中英

Clojure Vector of Refs

What's the simplest way to create a vector of distinct refs?

Using (repeat 5 (ref nil)) will return a list, but they will all reference the same ref:

user=> (repeat 5 (ref nil))
(#<Ref@16ef71: nil> #<Ref@16ef71: nil> #<Ref@16ef71: nil> #<Ref@16ef71: nil> #<R
ef@16ef71: nil>)

Same result with (replicate 5 (ref nil)) :

user=> (replicate 5 (ref nil))
(#<Ref@1d88db7: nil> #<Ref@1d88db7: nil> #<Ref@1d88db7: nil> #<Ref@1d88db7: nil>
 #<Ref@1d88db7: nil>)
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)))
(#<Ref@1f10a67: nil> #<Ref@1e2161d: nil> #<Ref@1a034d: nil> #<Ref@1cee792: nil> #<Ref@c5577c: nil>)
us

Ok, this is pretty gross, but it works:

user=> (map (fn [_] (ref nil)) (range 5))
(#<Ref@27147d: nil> #<Ref@b248c8: nil> #<Ref@c86116: nil> #<Ref@5e06ef: nil> #<Ref@19719f: nil>)

That returns a LazySeq, so if you want/need a Vector, then just use:

user=> (vec (map (fn [_] (ref nil)) (range 5)))
[#<Ref@5bf9cf: nil> #<Ref@6dbfb0: nil> #<Ref@43f787: nil> #<Ref@2fe9bf: nil> #<Ref@9b1e15: nil>]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM