11

Is there a Haskell library that allows me to have a Map from ranges to values? (Preferable somewhat efficient.)

let myRangeMap = RangeMap [(range 1 3, "foo"),(range 2 7, "bar"),(range 9 12, "baz")]
in  rangeValues 2
==> ["foo","bar"]
mrueg
  • 8,185
  • 4
  • 44
  • 66

3 Answers3

8

I've written a library to search in overlapping intervals because the existing ones did not fit my needs. I think it may have a more approachable interface than for example SegmentTree:

https://www.chr-breitkopf.de/comp/IntervalMap/index.html

It's also available on Hackage: https://hackage.haskell.org/package/IntervalMap

Chris
  • 4,133
  • 30
  • 38
7

Perhaps the rangemin library does what you want?

Good old Data.Map (and its more efficient Data.IntMap cousin) has a function

splitLookup :: Ord k => k -> Map k a -> (Map k a, Maybe a, Map k a)

which splits a map into submaps of keys less than / greater than a given key. This can be used for certain kinds of range searching.

keegan
  • 1,617
  • 10
  • 13
  • Yes, Data.Map certainly is useful here. I've used this quite successfully for "closest address to" type routing of network messages. the `minView` and `maxView` along with their `*WithKeys` cousins are also useful. – Thomas M. DuBuisson Oct 08 '10 at 21:48
  • `lookupLE` and friends (which are newer than this answer) are more efficient for this purpose when applicable, because they don't need to build new trees. – dfeuer Nov 12 '19 at 18:46
7

This task is called a stabbing query on a set of intervals. An efficient data structure for it is called (one-dimensional) segment tree.

The SegmentTree package provides an implementation of this data structure, but unfortunately I cannot figure out how to use it. (I feel that the interface of this package does not provide the right level of abstraction.)

Tsuyoshi Ito
  • 1,288
  • 11
  • 14