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]
"abc"

julia> d[11]
"def"

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.

yes:

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}()
IntervalTrees.IntervalBTree{Int64,IntervalValue{Int64,String},64}

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

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

julia> xs[(1001,10000)] = "High"
"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
Stacktrace:
 [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.