hesham
November 29, 2018, 7:07pm
1
Hi,
I have a function that I want to work on ranges and Vectors.
I see UnitRange{Int64} and Arrays{Int64,1} type hierarchy intersect at AbstractArray{Int64,1}, so I wrote my function as:
function test(t::AbstractArray{T,1}) where T
return T
end
julia> test([1:3])
UnitRange{Int64}
julia> test([1,2,3])
Int64
I was expecting to see Int64 as a result for both.
Any explanation?
mbauman
November 29, 2018, 7:19pm
2
In Julia, the 1:3
itself is a UnitRange.
When you put brackets around it, it means you’re putting the UnitRange into an array:
julia> A = [1:3]
1-element Array{UnitRange{Int64},1}:
1:3
julia> [1:3,5:7]
2-element Array{UnitRange{Int64},1}:
1:3
5:7
Just do test(1:3)
and you’ll find things to work as you expected.
Note that we print UnitRanges just like they’re entered, but they really are fully-functional array-like objects. You can see this by converting them to an Array
or doing maths on them:
julia> r = 1:3
1:3
julia> size(r)
(3,)
julia> Array(r)
3-element Array{Int64,1}:
1
2
3
julia> r .^ 2
3-element Array{Int64,1}:
1
4
9
1 Like
hesham
November 29, 2018, 7:59pm
3
This is indeed the issue. Thanks!