Skip to content

Commit

Permalink
Backport reshape and ntuple Val() APIs to 0.5 and 0.6 (#399)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbauman authored and ararslan committed Aug 28, 2017
1 parent 01d73db commit 226bb43
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]).
Expand Down
5 changes: 5 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 226bb43

Please sign in to comment.