diff --git a/README.md b/README.md index 25e340b3c3c58..5c83c5a02d8a1 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,8 @@ Currently, the `@compat` macro supports the following syntaxes: * `Val(x)` constructs `Val{x}()`. ([#22475]) +* The `reshape` and `ntuple` APIs are extended to support `Val{x}()` arguments on 0.6 and below. + * `chol` and `chol!` for `UniformScalings` ([#22633]). * `logdet` for `Number`s ([#22629]). diff --git a/src/Compat.jl b/src/Compat.jl index d17b59cfa09f8..4e406b4f5d087 100644 --- a/src/Compat.jl +++ b/src/Compat.jl @@ -461,6 +461,11 @@ end if VERSION < v"0.7.0-DEV.843" import Base: Val (::Type{Val})(x) = (Base.@_pure_meta; Val{x}()) + # Also add methods for Val(x) that were previously Val{x} + import Base: reshape + reshape{N}(parent::AbstractArray, ndims::Val{N}) = reshape(parent, Val{N}) + import Base: ntuple + ntuple{F,N}(f::F, ::Val{N}) = ntuple(f, Val{N}) end # https://github.com/JuliaLang/julia/pull/22629 diff --git a/test/runtests.jl b/test/runtests.jl index bc0099145ed6b..cefaa02634aa4 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -684,6 +684,30 @@ begin @test firstlast(Val(false)) == "Last" end +# Reshape to a given number of dimensions using Val(N) +# 0.7 +let + for A in (rand(()), rand(2), rand(2,3), rand(2,3,5), rand(2,3,5,7)), N in (1,2,3,4,5,6) + B = @inferred reshape(A, Val(N)) + @test ndims(B) == N + if N < ndims(A) + new_sz = (size(A)[1:N-1]..., prod(size(A)[N:end])) + elseif N == ndims(A) + new_sz = size(A) + else + new_sz = (size(A)..., ntuple(x->1, N-ndims(A))...) + end + @test size(B) == new_sz + @test B == reshape(A, new_sz) + end +end + +# ntuple with Val(N) +# 0.7 +@test @inferred(ntuple(x->1, Val(3))) == (1,1,1) +@test @inferred(ntuple(x->x, Val(0))) == () +@test @inferred(ntuple(x->x, Val(5))) == (1,2,3,4,5) + # @nospecialize # 0.7 no_specialize(@nospecialize(x)) = sin(1)