HaskellWiki

Haskell | Wiki community | Recent changes
Random page | Special pages

 

Not logged in
Log in | Help

Key-value apply

Categories: How to | Code

1 The problem / code

Consider the function:

apply :: (Ord k) => k -> v -> (v -> v) -> [(k,v)] -> [(k,v)]
apply k v f ds =
  let (p1,px) = span ( (k >) . fst) ds
      (p2,p3) = case px of
        []     -> ((k,v),[])
        (x:xs) -> if fst x == k
           then ((k, f $ snd x), xs)
           else ((k, v),       x:xs)
  in  p1 ++ (p2 : p3)

This takes a list of key/value pairs and processes it as follows:

Notice that if you start with a completely empty list, you can call apply several times and you will end up with a sorted list. apply uses the fact that the list is sorted to cut the search short in the 'I can't find it' case - hence the Ord context.

However, Haskell already provides this and much more functionality.

2 The solution: Data.Map

When you are making excessive use of (key,value) pairs it is usually time to switch to Data.Map. The apply function is almost the same as Data.Map.insertWith, only that function has the type:

insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a

Here the update function receives the new value as well.

Retrieved from "http://haskell.org/haskellwiki/Key-value_apply"

This page has been accessed 786 times. This page was last modified 18:36, 16 February 2007. Recent content is available under a simple permissive license.