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 | 6133 reads
|
Browse archives
Active forum topics |
Recent comments
25 weeks 6 days ago
26 weeks 1 hour ago
26 weeks 1 hour ago
48 weeks 1 day ago
1 year 2 days ago
1 year 1 week ago
1 year 1 week ago
1 year 4 weeks ago
1 year 9 weeks ago
1 year 9 weeks ago