Changes between Initial Version and Version 2 of Ticket #665
 Timestamp:
 Jan 30, 2006 10:41:43 AM (9 years ago)
Legend:
 Unmodified
 Added
 Removed
 Modified

Ticket #665
 Property Keywords collections added

Ticket #665 – Description
initial v2 2 2 and I quite like it. Often though, I find myself needing a function 3 3 that behaves like this: 4 4 {{{ 5 5 > import Data.Map (Map); import qualified Data.Map as Map hiding (Map) 6 6 > … … 8 8 > insert1 k f m = let v = f (Map.lookup k m) 9 9 > in (v, Map.insert k v m) 10 10 }}} 11 11 In words, we use a function to determine what to place in the map, 12 12 depending on what is already in the map. In the result, we return 13 13 the new map, and the value that was inserted in the map. Here is an 14 14 example of how we may use this function: 15 15 {{{ 16 16 > example m = insert1 0 v m 17 17 > where v Nothing = 0 18 18 > v (Just n) = n + 1 19 19 }}} 20 20 Clearly, I can implement this function myself as above. However, I was 21 21 wondering if I can achieve the same, without searching in the map twice. 22 22 I came up with the following: 23 23 {{{ 24 24 > insert2 :: Ord k => k > (Maybe v > v) > Map k v > (v, Map k v) 25 25 > insert2 k f m = (v,m') … … 28 28 > (r, m') = Map.insertLookupWithKey g k v m 29 29 > g _ x _ = x 30 30 }}} 31 31 Is there a more direct way to implement this function? The use of lazyness 32 32 in this case seems like an overkill. If not, I would like to suggest that we … … 34 34 the library are quite easy to implement in terms of this function, 35 35 so perhaps they don't need to be in the API? 36 36 {{{ 37 37 > insertWith' :: Ord k => (v > v > v) > k > v > Map k v > Map k v 38 38 > insertWith' f k v m = snd (insert2 k (maybe v (f v)) m) … … 40 40 > insertWithKey' :: Ord k => (k > v > v > v) > k > v > Map k v > Map k v 41 41 > insertWithKey' f k v m = snd (insert2 k (maybe v (f k v)) m) 42 }}}