Changes between Initial Version and Version 2 of Ticket #665


Ignore:
Timestamp:
Jan 30, 2006 10:41:43 AM (8 years ago)
Author:
jpbernardy
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #665

    • Property Keywords collections added
  • Ticket #665 – Description

    initial v2  
    22and I quite like it.  Often though, I find myself needing a function 
    33that behaves like this: 
    4  
     4{{{ 
    55> import Data.Map (Map); import qualified Data.Map as Map hiding (Map) 
    66> 
     
    88> insert1 k f m   = let v = f (Map.lookup k m) 
    99>                   in (v, Map.insert k v m) 
    10  
     10}}} 
    1111In words, we use a function to determine what to place in the map, 
    1212depending on what is already in the map.  In the result, we return 
    1313the new map, and the value that was inserted in the map.  Here is an 
    1414example of how we may use this function: 
    15  
     15{{{ 
    1616> example m           = insert1 0 v m 
    1717>   where v Nothing   = 0 
    1818>         v (Just n)  = n + 1 
    19  
     19}}} 
    2020Clearly, I can implement this function myself as above.  However, I was 
    2121wondering if I can achieve the same, without searching in the map twice. 
    2222I came up with the following: 
    23  
     23{{{ 
    2424> insert2 :: Ord k => k -> (Maybe v -> v) -> Map k v -> (v, Map k v) 
    2525> insert2 k f m   = (v,m') 
     
    2828>   (r, m')       = Map.insertLookupWithKey g k v m 
    2929>   g _ x _       = x 
    30  
     30}}} 
    3131Is there a more direct way to implement this function?  The use of lazyness 
    3232in this case seems like an overkill.  If not, I would like to suggest that we 
     
    3434the library are quite easy to implement in terms of this function, 
    3535so perhaps they don't need to be in the API? 
    36  
     36{{{ 
    3737> insertWith' :: Ord k => (v -> v -> v) -> k -> v -> Map k v -> Map k v 
    3838> insertWith' f k v m = snd (insert2 k (maybe v (f v)) m) 
     
    4040> insertWithKey' :: Ord k => (k -> v -> v -> v) -> k -> v -> Map k v -> Map k v 
    4141> insertWithKey' f k v m = snd (insert2 k (maybe v (f k v)) m) 
     42}}}