insert +Data.Map
O(log n). Insert a new key and value in the map. If the key is already present in the map, the associated value is replaced with the supplied value. insert is equivalent to insertWith const.
> insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
> insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
> insert 5 'x' empty == singleton 5 'x'
O(log n). Combines insert operation with old value retrieval. The expression (insertLookupWithKey f k x map) is a pair map</tt>) and the second element equal to (insertWithKey f k x map).
> let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
> insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
> insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
> insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
This is how to define insertLookup using insertLookupWithKey:
> let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
> insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
> insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
O(log n). Insert with a function, combining new value and old value. insertWith f key value mp will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key, f new_value old_value).
> insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
> insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
> insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
Deprecated. As of version 0.5, replaced by insertWith.
O(log n). Same as insertWith, but the combining function is applied strictly. This is often the most desirable behavior.
For example, to update a counter:
> insertWith' (+) k 1 m
O(log n). Insert with a function, combining key, new value and old value. insertWithKey f key value mp will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key,f key new_value old_value). Note that the key passed to f is the same key passed to insertWithKey.
> let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
> insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
> insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
> insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
Deprecated. As of version 0.5, replaced by insertWithKey.
O(log n). Same as insertWithKey, but the combining function is applied strictly.