User loginNavigation |
Optimal map APIThis has just crossed my mind: Functional APIs and imperative ones often differ in the way that functional ones make use of function-passing as a way to manipulate data. For example, in Haskell, there's filter: filter :: (a -> Bool) -> [a] -> [a] Used like this: filter somecondition oldlist For lists, this can be simulated in say, Java by using:
ListIterator<E> it = list.listIterator();
while(it.hasNext()) {
if(!somecondition(it.next())) {
it.remove();
}
}
While it is possible to implement this and other operations on lists equally fast, it doesn't seem to be the case for maps. Consider the following task: alter :: (Maybe a -> Maybe a) -> k -> Map k a -> Map k a In this case:
alter (\x -> case x of
Just v -> if v < n
then Nothing
else Just (v+n)
Nothing -> Just n) str oldmap This traverses the tree exactly once, while my Java implementation
Integer value = map.get(str);
if(value==null) {
map.put(str,n);
}
else {
if(value<n) {
map.remove(str);
}
else {
map.put(str,n+value);
}
}
traverses the map twice(once for retrieval, once for insertion/deletion). By Henning G at 2006-12-11 00:15 | LtU Forum | previous forum topic | next forum topic | other blogs | 6380 reads
|
Browse archives
Active forum topics |
Recent comments
15 hours 4 min ago
15 hours 19 min ago
5 days 16 hours ago
5 days 16 hours ago
5 days 16 hours ago
3 weeks 6 days ago
4 weeks 4 days ago
4 weeks 4 days ago
4 weeks 6 days ago
4 weeks 6 days ago