Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow map!(f, array) #40632

Merged
merged 8 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)`.

LilithHafner marked this conversation as resolved.
Show resolved Hide resolved
# 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
Loading