Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>)
like image 584
Kai Avatar asked Jun 24 '09 17:06

Kai


2 Answers

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
like image 100
Brian Carper Avatar answered Sep 22 '22 03:09

Brian Carper


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>]
like image 42
Dan Avatar answered Sep 23 '22 03:09

Dan