In Java 1.6, the NavigableMap (and the NavigableSet) interfaces were introduced and TreeMap was updated to implement the new interface. Among other things, NavigableMap is useful for asking questions like "Which element in the collection is closest to X? (see this excellent blog post by François Sarradin for an example and discussion).
I was hoping to find something similar in Scala 2.8's TreeMap implementation, but alas, it doesn't appear to be so (at least, it isn't obvious). Is there another Scala class or trait which is similar to Java's NavigableMap? If not, are there some simple Scala idioms which can be used to achieve something similar?
I realize I can use Java's TreeMap, but I'd like to stay within the Scala collections framework (if only for simplicity).
NavigableMap is an extension of the SortedMap collection framework. It is used to arrange the elements in a uniform fashion. NavigableMap has different methods to iterate over the elements in the Map.
A NavigableMap may be accessed and traversed in either ascending or descending key order. The descendingMap method returns a view of the map with the senses of all relational and directional methods inverted. The performance of ascending operations and views is likely to be faster than that of descending ones.
On immutable collections, having the back references makes it impossible to make the collection persistent. So, instead, people use zippers to navigate through such structures. Anti-xml has a nice example of using zippers when working with XML.
Here's a thread on this topic
It seems SortedMap
might be able to get you part of the way there, but what I've tested so far I'm not sure if it's O(log(n)) the way a search ought to be:
def searchMap(m: SortedMap[Int,_], k: Int) = {
val left = m to(k) lastKey
val right = m from(k) take(2) lastKey
if (k - left < right - k)
left
else
right
}
Based on the definitions of from
and to
in terms of rangeImpl it looks like this could be O(log(n)), but based on actually timing it, it appears to grow linearly for all plausible values of n.
So I'm not sure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With