Assigning to a slice and taking a slice are completely different operations, they merely have similar syntax. After parsing, these two operations are lowered to two different function calls, `setindex!` and `getindex`. The former modifies the array, while the latter creates a new array.
There has been a recent discussion whether taking a slice should return a subarray or should return a new array. The outcome is still very much in the open; people are currently collecting data (i.e. studying real-world code examples) to see which variant is "better", in the sense of "more likely to avoid programming errors" and "runs faster in general". As is, if the difference between these two isn't already highlighted in the documentation, it definitively should be. -erik On Tue, Mar 8, 2016 at 6:11 AM, Daniel Carrera <[email protected]> wrote: > Hello, > > Is there any difference besides the obvious one that assigning to a slice > modifies the array? What I mean is, is there a difference in the internals > or how it works that I should be aware of? Up until this thread I had been > under the impression that a slice was a type of link/alias to the original > array, and that's still my mental picture of how assignment to a slice > works. > > Thanks. > > > On 8 March 2016 at 04:02, Stefan Karpinski <[email protected]> wrote: >> >> Assigning to slice is quite different from taking a slice. >> >> On Mon, Mar 7, 2016 at 9:49 PM, Daniel Carrera <[email protected]> wrote: >>> >>> That is not literally true: >>> >>> vals[2:3] = vals[3:4] >>> >>> >>> On Tuesday, 8 March 2016 02:37:26 UTC+1, John Myles White wrote: >>>> >>>> Array indexing produces a brand new array that has literally no >>>> relationship with the source array. >>>> >>>> -- John >>>> >>>> On Monday, March 7, 2016 at 5:21:34 PM UTC-8, Daniel Carrera wrote: >>>>> >>>>> Hello, >>>>> >>>>> Some Julia functions act on their inputs. For example: >>>>> >>>>> julia> vals = [6,5,4,3] >>>>> 4-element Array{Int64,1}: >>>>> 6 >>>>> 5 >>>>> 4 >>>>> 3 >>>>> >>>>> julia> sort!(vals); >>>>> >>>>> julia> vals >>>>> 4-element Array{Int64,1}: >>>>> 3 >>>>> 4 >>>>> 5 >>>>> 6 >>>>> >>>>> >>>>> However, it looks like these functions do not modify array slices: >>>>> >>>>> julia> vals = [6,5,4,3] >>>>> 4-element Array{Int64,1}: >>>>> 6 >>>>> 5 >>>>> 4 >>>>> 3 >>>>> >>>>> julia> sort!(vals[2:end]) >>>>> 3-element Array{Int64,1}: >>>>> 3 >>>>> 4 >>>>> 5 >>>>> >>>>> julia> vals >>>>> 4-element Array{Int64,1}: >>>>> 6 >>>>> 5 >>>>> 4 >>>>> 3 >>>>> >>>>> >>>>> Can anyone explain to me why this happens? Is this a language feature? >>>>> Is it at all possible to make a destructive function that acts on slices? >>>>> >>>>> Cheers, >>>>> Daniel. >>>>> >> > -- Erik Schnetter <[email protected]> http://www.perimeterinstitute.ca/personal/eschnetter/
