[Haskell-cafe] Data.Map add only if not exist and return true if added

Arthur van Leeuwen arthurvl at cs.uu.nl
Tue Dec 9 04:13:52 EST 2008


On 9 dec 2008, at 09:11, John Ky wrote:

> Hi,
>
> I'm looking for a function for Data.Map that will insert a new key  
> and value into the map if the key doesn't already exist in the map.   
> When the key already exists, I don't want the value updated in the  
> map.  Additionally, I want to know whether the key/value was  
> inserted or not so that I can return that fact as a boolean from my  
> function.
>
> I can't work out which function in Data.Map is suitable for this  
> task and I wanted to avoid two lookups.

Data.Map.insertLookupWithKey (\k n o -> o)
should do the trick. The first element of the tuple returned
is the Maybe a that is Nothing if no value existed at the given key,
the second element is the updated map.

With kind regards, Arthur.

-- 

   /\    / |       arthurvl at cs.uu.nl       | Work like you don't need  
the money
/__\  /  | A friend is someone with whom | Love like you have never  
been hurt
/    \/__ | you can dare to be yourself   | Dance like there's nobody  
watching





More information about the Haskell-Cafe mailing list