A comprehension by default creates an vector.
Sometimes though I use comprehension as an one-line mutating procedure.
e.g.:
a = collect(1:100)
# my one-liner mutating comprehension
deletespec!(a,v) = [deleteat!(a, x) for x in v];
Clearly here, I am not interested in the result.
I just want the mutating operation to happen.
Calling it will return a vector, which means something got allocated, that I didn't really need
julia> deletespec!(a, [1,2,3])
[[2, 4, 6, 7, 8, 9, 10, 11, 12, 13 … 91, 92, 93, 94, 95, 96, 97, 98, 99, 100], [2, 4, 6, 7, 8, 9, 10, 11, 12, 13 … 91, 92, 93, 94, 95, 96, 97, 98, 99, 100], [2, 4, 6, 7, 8, 9, 10, 11, 12, 13 … 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]
Is there a way to produce comprehensions that return nothing, i.e. allocate nothing ?
Should I even worry about this performance-wise ?
PS I know what I am doing to delete multiple indices is wrong and there are better ways to do that, but please don't focus on this.
A comprehension by default creates an vector.
Sometimes though I use comprehension as an one-line mutating procedure.
e.g.:
a = collect(1:100)
# my one-liner mutating comprehension
deletespec!(a,v) = [deleteat!(a, x) for x in v];
Clearly here, I am not interested in the result.
I just want the mutating operation to happen.
Calling it will return a vector, which means something got allocated, that I didn't really need
julia> deletespec!(a, [1,2,3])
[[2, 4, 6, 7, 8, 9, 10, 11, 12, 13 … 91, 92, 93, 94, 95, 96, 97, 98, 99, 100], [2, 4, 6, 7, 8, 9, 10, 11, 12, 13 … 91, 92, 93, 94, 95, 96, 97, 98, 99, 100], [2, 4, 6, 7, 8, 9, 10, 11, 12, 13 … 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]
Is there a way to produce comprehensions that return nothing, i.e. allocate nothing ?
Should I even worry about this performance-wise ?
PS I know what I am doing to delete multiple indices is wrong and there are better ways to do that, but please don't focus on this.
Would a generator work here?
you mean writing (deleteat!(a, x) for x in v)
instead of [deleteat!(a, x) for x in v]
. It would work but again it feels like there is some effort going somewhere (e.g. constructing the generator) which is unneeded.
wait no, it wouldn't work.
the mutation will happen only when I start iterating the elements of the generator.
Why not use foreach
?
Yes, this is a good suggestion.. However nested foreach
will get ugly. Comprehensions are easier to follow in that regard..
Nested foreach
using the do
construction shouldn't be that ugly, or am I missing something?
Nested list comprehensions would also get pretty ugly pretty fast
Last updated: Dec 28 2024 at 04:38 UTC