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

Specialize map for eltype conversions of a ReshapedArray #40678

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions base/reshapedarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -395,3 +395,6 @@ function merge_adjacent_dim(apsz::Dims{N}, apst::Dims{N}, n::Int = 1) where {N}
end
return sz, st, n
end

## ReshapedArrays may forward a mapped function to the parent
map(f, R::ReshapedArray) = ReshapedArray(map(f, parent(R)), R.dims, R.mi)
30 changes: 30 additions & 0 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2129,3 +2129,33 @@ end
@test one(Mat([1 2; 3 4])) == Mat([1 0; 0 1])
@test one(Mat([1 2; 3 4])) isa Mat
end

@testset "map on a ReshapedArray (PR #40678)" begin
# Ranges have special map methods for eltype conversion
# reshaped ranges may utilize these
r = 1:4
R = reshape(r, 2, 2)
for T in [Float64, BigInt]
S = map(T, R)
@test eltype(S) == T
@test S == R
@test parent(S) isa AbstractRange
end

# in general for Arrays, map(f, R) and map(x -> f(x), R) should behave identically
# and the result should match map(f, collect(R))
R = reshape(reinterpret(Float64, ComplexF64[i for i = 1:4]), 1, :)
C = collect(R)
for T in [Int, BigInt], f in [T, x -> T(x)]
S = map(f, R)
@test eltype(S) == T
@test S == R
@test S == map(f, C)
end

R = reshape(1:4, 4, 1)
for f in [CartesianIndex, x -> CartesianIndex(x)]
RR = map(f, R)
@test RR == map(f, collect(R))
end
end