Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What UnitRange Type in Julia mean?

Tags:

julia

I try to read Julia code having OOP strongly typed backgrownd. I get most of it, yet UnitRange{Int}; and the way it is used are not clear for me: is it an array or just an an integer? Can any one present an analog of UnitRange type in some strongly typed language?

like image 342
DuckQueen Avatar asked Sep 06 '25 13:09

DuckQueen


1 Answers

Let's just have a look. We can create a UnitRange{Int} explicitly by calling it's constructor

julia> UnitRange{Int}(3,5) # equivalent to just saying 3:5
3:5

julia> typeof(ans)
UnitRange{Int64}

Using the @which macro we can find out where the constructor and the type are defined:

julia> @which UnitRange{Int}(3,5)
(::Type{UnitRange{T}})(start, stop) where T<:Real in Base at range.jl:255

namely in range.jl line 255. There we find (@edit might be useful):

struct UnitRange{T<:Real} <: AbstractUnitRange{T}
    start::T
    stop::T
    UnitRange{T}(start, stop) where {T<:Real} = new(start, unitrange_last(start,stop))
end

Hence it really is two integers for T = Int64. Using the same technique we can find out that iterating and indexing of UnitRanges is defined in the same file from line 563 on. Therefore, a UnitRange{Int} is a type with two integer fields which defines an indexing and iterator interface. See https://docs.julialang.org/en/stable/manual/interfaces/index.html for more information on interfaces.

like image 115
carstenbauer Avatar answered Sep 11 '25 03:09

carstenbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!