Skip to content

Commit

Permalink
Allow map!(f, array) (#40632)
Browse files Browse the repository at this point in the history
...there's really no sensible interpretation of `map!(f, array)` other than `map!(f, array, array)`.

---------

Co-authored-by: Lilith Orion Hafner <lilithhafner@gmail.com>
  • Loading branch information
mcabbott and LilithHafner authored Jan 8, 2025
1 parent 98dc249 commit 38b41b5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ New library features
* `invoke` now supports passing a CodeInstance instead of a type, which can enable
certain compiler plugin workflows ([#56660]).
* `sort` now supports `NTuple`s ([#54494])
* `map!(f, A)` now stores the results in `A`, like `map!(f, A, A)`. or `A .= f.(A)` ([#40632]).

Standard library changes
------------------------
Expand Down
25 changes: 23 additions & 2 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3503,11 +3503,32 @@ julia> map!(+, zeros(Int, 5), 100:999, 1:3)
```
"""
function map!(f::F, dest::AbstractArray, As::AbstractArray...) where {F}
isempty(As) && throw(ArgumentError(
"""map! requires at least one "source" argument"""))
@assert !isempty(As) # should dispatch to map!(f, A)
map_n!(f, dest, As)
end

"""
map!(function, array)
Like [`map`](@ref), but stores the result in the same array.
!!! compat "Julia 1.12"
This method requires Julia 1.12 or later. To support previous versions too,
use the equivalent `map!(function, array, array)`.
# Examples
```jldoctest
julia> a = [1 2 3; 4 5 6];
julia> map!(x -> x^3, a);
julia> a
2×3 Matrix{$Int}:
1 8 27
64 125 216
```
"""
map!(f::F, inout::AbstractArray) where F = map!(f, inout, inout)

"""
map(f, A::AbstractArray...) -> N-array
Expand Down
2 changes: 1 addition & 1 deletion test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -908,7 +908,7 @@ test_ind2sub(TestAbstractArray)

include("generic_map_tests.jl")
generic_map_tests(map, map!)
@test_throws ArgumentError map!(-, [1])
@test map!(-, [1]) == [-1]

test_UInt_indexing(TestAbstractArray)
test_13315(TestAbstractArray)
Expand Down

0 comments on commit 38b41b5

Please sign in to comment.