From ed24a4564b65e3158310397f896b9ddce3d8b771 Mon Sep 17 00:00:00 2001 From: Christof Stocker Date: Fri, 5 Aug 2016 20:34:08 +0200 Subject: [PATCH] Fix #16519 by adding missing convert methods This commit will allow a user to call: ```julia convert(Vector, my_abstractvector_of_eltype_Foo) convert(Matrix, my_abstractmatrix_of_eltype_Foo) ``` which is useful because - for the case that the variable is a subarray of the same dimensionality - for consistency with PR #17066 The same effect can (and could before this commit) also be achieved in the following manner. Note how the two last lines are unnecessarily verbose, because the eltype can be inferred ```julia convert(Array, my_abstractvector_of_eltype_Foo) convert(Array, my_abstractmatrix_of_eltype_Foo) convert(Vector{Foo}, my_abstractvector_of_eltype_Foo) convert(Matrix{Foo}, my_abstractmatrix_of_eltype_Foo) ``` --- base/array.jl | 3 +++ test/abstractarray.jl | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/base/array.jl b/base/array.jl index 079bdfd1e5d99..4a6da86600584 100644 --- a/base/array.jl +++ b/base/array.jl @@ -192,6 +192,9 @@ end ## Conversions ## +convert{T}(::Type{Vector}, x::AbstractVector{T}) = convert(Vector{T}, x) +convert{T}(::Type{Matrix}, x::AbstractMatrix{T}) = convert(Matrix{T}, x) + convert{T,n}(::Type{Array{T}}, x::Array{T,n}) = x convert{T,n}(::Type{Array{T,n}}, x::Array{T,n}) = x diff --git a/test/abstractarray.jl b/test/abstractarray.jl index b3ff1b2f18c77..805874337bda0 100644 --- a/test/abstractarray.jl +++ b/test/abstractarray.jl @@ -405,7 +405,19 @@ function test_primitives{T}(::Type{T}, shape, ::Type{TestAbstractArray}) # convert{T, N}(::Type{Array}, A::AbstractArray{T, N}) X = [1:10...] + Y = [1 2; 3 4] @test convert(Array, X) == X + @test convert(Array, Y) == Y + + # convert{T}(::Type{Vector}, A::AbstractVector{T}) + @test convert(Vector, X) == X + @test convert(Vector, view(X, 2:4)) == [2,3,4] + @test_throws MethodError convert(Vector, Y) + + # convert{T}(::Type{Matrix}, A::AbstractMatrix{T}) + @test convert(Matrix, Y) == Y + @test convert(Matrix, view(Y, 1:2, 1:2)) == Y + @test_throws MethodError convert(Matrix, X) end function test_in_bounds(::Type{TestAbstractArray})