Tutorial :Clojure Vector of Refs



Question:

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


Solution:1

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  


Solution:2

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »