`sortrows` and `sortcols` on `SubArrays`


#1

Is there any reason the functions sortrows and sortcols don’t work on SubArrays?

julia> versioninfo()
Julia Version 0.6.0
Commit 903644385b (2017-06-19 13:05 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin13.4.0)
  CPU: Intel(R) Core(TM) i7-6920HQ CPU @ 2.90GHz
  WORD_SIZE: 64
  BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell)
  LAPACK: libopenblas64_
  LIBM: libopenlibm
  LLVM: libLLVM-3.9.1 (ORCJIT, skylake)

julia> srand(123); A = rand(0:1, 5, 3)
5×3 Array{Int64,2}:
 0  1  1
 0  0  1
 0  1  1
 0  0  0
 1  1  0

julia> Av = view(A, [2; 4; 5], [2; 3])
3×2 SubArray{Int64,2,Array{Int64,2},Tuple{Array{Int64,1},Array{Int64,1}},false}:
 0  1
 0  0
 1  0

julia> sortrows(Av)
ERROR: MethodError: Cannot `convert` an object of type SubArray{Int64,1,Array{Int64,2},Tuple{Int64,Array{Int64,1}},false} to an object of type SubArray{Int64,1,SubArray{Int64,2,Array{Int64,2},Tuple{Array{Int64,1},Array{Int64,1}},false},Tuple{Int64,Base.Slice{Base.OneTo{Int64}}},false}
This may have arisen from a call to the constructor SubArray{Int64,1,SubArray{Int64,2,Array{Int64,2},Tuple{Array{Int64,1},Array{Int64,1}},false},Tuple{Int64,Base.Slice{Base.OneTo{Int64}}},false}(...),
since type constructors fall back to convert methods.
Stacktrace:
 [1] #sortrows#14(::Array{Any,1}, ::Function, ::SubArray{Int64,2,Array{Int64,2},Tuple{Array{Int64,1},Array{Int64,1}},false}) at ./sort.jl:776
 [2] sortrows(::SubArray{Int64,2,Array{Int64,2},Tuple{Array{Int64,1},Array{Int64,1}},false}) at ./sort.jl:772

Similar for sortcols.


#2

This is a bug. Here is the definition of sortrows:

function sortrows(A::AbstractMatrix; kws...)
    inds = indices(A,1)
    T = slicetypeof(A, inds, :)
    rows = similar(Vector{T}, indices(A, 1))
    for i in inds
        rows[i] = view(A, i, :)
    end
    p = sortperm(rows; kws..., order=Lexicographic)
    A[p,:]
end

Base.Sort.slicetypeof returns the wrong type for a SubArray so types don’t match in rows[i] = view(A, i, :)


#3

All right. I’ll open an issue if nobody disagrees it’s bug for another day or two.


#4

Opened an issue https://github.com/JuliaLang/julia/issues/22493