Skip to content

Commit

Permalink
allow arbitrary functions in map
Browse files Browse the repository at this point in the history
  • Loading branch information
jishnub committed Mar 9, 2024
1 parent 2180cf5 commit 5fdd73e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
5 changes: 2 additions & 3 deletions base/reshapedarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,5 @@ function merge_adjacent_dim(apsz::Dims{N}, apst::Dims{N}, n::Int = 1) where {N}
return sz, st, n
end

## ReshapedArray eltype conversion

map(::Type{T}, R::ReshapedArray) where {T} = ReshapedArray(map(T, parent(R)), R.dims, R.mi)
## ReshapedArrays may forward a mapped function to the parent
map(f, R::ReshapedArray) = ReshapedArray(map(f, parent(R)), R.dims, R.mi)
19 changes: 15 additions & 4 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2051,7 +2051,9 @@ end
test_unsetindex(MyMatrixUnsetIndexLinInds)
end

@testset "eltype conversion for ReshapedArray" begin
@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]
Expand All @@ -2061,11 +2063,20 @@ end
@test parent(S) isa AbstractRange
end

# a more complicated case
# 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, :)
for T in [Int, BigInt]
S = map(T, R)
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

0 comments on commit 5fdd73e

Please sign in to comment.