Skip to content

Commit 38b41b5

Browse files
Allow map!(f, array) (#40632)
...there's really no sensible interpretation of `map!(f, array)` other than `map!(f, array, array)`. --------- Co-authored-by: Lilith Orion Hafner <[email protected]>
1 parent 98dc249 commit 38b41b5

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ New library features
117117
* `invoke` now supports passing a CodeInstance instead of a type, which can enable
118118
certain compiler plugin workflows ([#56660]).
119119
* `sort` now supports `NTuple`s ([#54494])
120+
* `map!(f, A)` now stores the results in `A`, like `map!(f, A, A)`. or `A .= f.(A)` ([#40632]).
120121

121122
Standard library changes
122123
------------------------

base/abstractarray.jl

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3503,11 +3503,32 @@ julia> map!(+, zeros(Int, 5), 100:999, 1:3)
35033503
```
35043504
"""
35053505
function map!(f::F, dest::AbstractArray, As::AbstractArray...) where {F}
3506-
isempty(As) && throw(ArgumentError(
3507-
"""map! requires at least one "source" argument"""))
3506+
@assert !isempty(As) # should dispatch to map!(f, A)
35083507
map_n!(f, dest, As)
35093508
end
35103509

3510+
"""
3511+
map!(function, array)
3512+
3513+
Like [`map`](@ref), but stores the result in the same array.
3514+
!!! compat "Julia 1.12"
3515+
This method requires Julia 1.12 or later. To support previous versions too,
3516+
use the equivalent `map!(function, array, array)`.
3517+
3518+
# Examples
3519+
```jldoctest
3520+
julia> a = [1 2 3; 4 5 6];
3521+
3522+
julia> map!(x -> x^3, a);
3523+
3524+
julia> a
3525+
2×3 Matrix{$Int}:
3526+
1 8 27
3527+
64 125 216
3528+
```
3529+
"""
3530+
map!(f::F, inout::AbstractArray) where F = map!(f, inout, inout)
3531+
35113532
"""
35123533
map(f, A::AbstractArray...) -> N-array
35133534

test/abstractarray.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -908,7 +908,7 @@ test_ind2sub(TestAbstractArray)
908908

909909
include("generic_map_tests.jl")
910910
generic_map_tests(map, map!)
911-
@test_throws ArgumentError map!(-, [1])
911+
@test map!(-, [1]) == [-1]
912912

913913
test_UInt_indexing(TestAbstractArray)
914914
test_13315(TestAbstractArray)

0 commit comments

Comments
 (0)