Is there a dictionary-based data structure where the keys are disjoint ranges, and indexing with an integer looks up the matching range?

For example,

julia> d = Dict(1:4=>"abc",10:14=>"def")
Dict{UnitRange{Int64},String} with 2 entries:
  10:14 => "def"
  1:4   => "abc"

# What I want
julia> d[3]

julia> d[11]

julia> d[5]
ERROR: KeyError: key 5 not found

I couldn’t find any package that provides this after a brief search on Juliahub, and I’ll be grateful if someone could point one out. If there’s nothing then I’ll create a package that implements this.


1 Like

Thanks, this looks promising. However I’m not sure if the package hasn’t been updated for a while, as it’s failing tests on julia1.2 and 1.4 (edit: there seems to be an issue filed about this). I’m also not sure how to use it, as a documentation example results in an error:

julia> using IntervalTrees

julia> # Create an interval tree mapping (Int, Int) intervals to Strings.
       xs = IntervalMap{Int, String}()

julia> # Insert values
       xs[(1,100)] = "Low"

julia> xs[(101,1000)] = "Medium"

julia> xs[(1001,10000)] = "High"

julia> # Search for values
       println(xs[(1001,10000)]) # prints "High"
ERROR: MethodError: no method matching getindex(::IntervalTrees.IntervalBTree{Int64,IntervalValue{Int64,String},64}, ::Tuple{Int64,Int64})
Closest candidates are:
  getindex(::IntervalTrees.IntervalBTree{K,V,B}, ::AbstractInterval{K}) where {K, V, B} at /home/jishnu/.julia/packages/IntervalTrees/wh2ex/src/map.jl:25
 [1] top-level scope at REPL[9]:2

Sorry, not sure what’s up with that. I think I’m using it successfully, but maybe I’m stuck on an older version. Hopefully the maintainers might ping in. BioJulia is a largeish and awesome organization.