Skip to content

Commit a48676c

Browse files
authored
Merge pull request #17154 from JuliaLang/sb/median-slice
Make `median` non-mutating on arrays.
2 parents 6651f78 + aaaf8fa commit a48676c

File tree

3 files changed

+10
-4
lines changed

3 files changed

+10
-4
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ Breaking changes
8484
If a reshaped copy is needed, use `copy(reshape(a))` or `copy!` to a new array of
8585
the desired shape ([#4211]).
8686

87+
* `mapslices` will always pass a view, so passing mutating functions will mutate the underlying array ([#16260])
88+
8789
* Local variables and arguments are represented in lowered code as numbered `Slot`
8890
objects instead of as symbols ([#15609]).
8991

base/statistics.jl

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -490,9 +490,10 @@ function median!{T}(v::AbstractVector{T})
490490
end
491491
end
492492
median!{T}(v::AbstractArray{T}) = median!(vec(v))
493-
494493
median{T}(v::AbstractArray{T}) = median!(copy!(Array(T, length(v)), v))
495-
median{T}(v::AbstractArray{T}, region) = mapslices(median!, v, region)
494+
495+
median!{T}(v::AbstractArray{T}, region) = mapslices(median!, v, region)
496+
median{T}(v::AbstractArray{T}, region) = median!(copy(v), region)
496497

497498
# for now, use the R/S definition of quantile; may want variants later
498499
# see ?quantile in R -- this is type 7

test/statistics.jl

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,10 @@ end
3232
@test median([1.,-1.,Inf,-Inf]) == 0.0
3333
@test isnan(median([-Inf,Inf]))
3434

35-
@test all(median([2 3 1 -1; 7 4 5 -4], 2) .== [1.5, 4.5])
36-
@test all(median([2 3 1 -1; 7 4 5 -4], 1) .== [4.5 3.5 3.0 -2.5])
35+
X = [2 3 1 -1; 7 4 5 -4]
36+
@test all(median(X, 2) .== [1.5, 4.5])
37+
@test all(median(X, 1) .== [4.5 3.5 3.0 -2.5])
38+
@test X == [2 3 1 -1; 7 4 5 -4] # issue #17153
3739

3840
@test_throws ArgumentError median([])
3941
@test isnan(median([NaN]))
@@ -44,6 +46,7 @@ end
4446
@test median!([1 2 3 4]) == 2.5
4547
@test median!([1 2; 3 4]) == 2.5
4648

49+
4750
@test invoke(median, (AbstractVector,), 1:10) == median(1:10) == 5.5
4851

4952
# mean

0 commit comments

Comments
 (0)