fill! with copies

195 views
Skip to first unread message

Carlos Becker

unread,
May 16, 2014, 4:27:18 AM5/16/14
to julia...@googlegroups.com
Hello all,

I wanted to create an array of an immutable type and initialize an empty copy in each (with the default constructor).
I am wondering which is the best way to do it, so far:

   immutable ChannVals
taus::Vector{Float64}
alphas::Vector{Float64}

ChannVals() = new( Float64[], Float64[] )
   end

   # create 10 new instances
   arr = ChannVals[ChannVals() for i=1:10]


Now, a neat but incorrect way is to do

   arr = Array( ChannVals, 10 )
   fill!(allVals, ChannVals())

because it will fill them with the same instance.
Is there a neat way, such as a fillwithcopies!() ?


Cheers.

Carlos Becker

unread,
May 16, 2014, 4:28:05 AM5/16/14
to julia-users
* correction, 'allVals'  is 'arr' in the last line of code.


------------------------------------------
Carlos

Tim Holy

unread,
May 16, 2014, 6:41:36 AM5/16/14
to julia...@googlegroups.com
Try

arr = [ChannVals() for i = 1:10]

Jameson Nash

unread,
May 16, 2014, 11:01:56 AM5/16/14
to julia...@googlegroups.com
Since they are immutable, fill! did exactly what you wanted

Ivar Nesje

unread,
May 16, 2014, 4:21:36 PM5/16/14
to julia...@googlegroups.com
@Jameson They are immutable, but they contain references to mutable arrays, and all the immutable types will reference the same arrays. That way you would not just need a copy but a deepcopy. That will probably be too much overhead for fill!(), and will be problematic if someone decided to fill! an array with some large structure.

On the other hand, I think it would be reasonable for fill! to take a shallow copy of mutable types. Not sure what others think on that subject though.

Ivar

Stefan Karpinski

unread,
May 16, 2014, 5:36:01 PM5/16/14
to Julia Users
When you write fill!(arr, ChannVals()) you are asking to fill arr with the one value that is the result of evaluating ChannVals() once. Doing anything else would be bizarre. We could have a version of fill! that takes a thunk so you could write

fill!(arr) do
  ChannVals()
end

That would have the desired effect as well, but it seems to me that using a comprehension is just as easy in that case.

Carlos Becker

unread,
May 18, 2014, 5:21:30 AM5/18/14
to julia-users
Thanks all, those look like neat solutions.


------------------------------------------
Carlos
Reply all
Reply to author
Forward
0 new messages