Keyvalue apply
From HaskellWiki
(Difference between revisions)
(Data.Map can be used) 
(Nice one...) 

Line 25:  Line 25:  
== Data.Map ==  == Data.Map ==  
−  When you are making excessive use of (key,value) pairs it is usually time to switch to Data.Map. <hask>apply</hask> is almost the same as <hask>Data.Map.insertWith</hask>, only that function has the type:  +  When you are making excessive use of (key,value) pairs it is usually time to switch to <hask>Data.Map</hask>. Your <hask>apply</hask> function is almost the same as <hask>Data.Map.insertWith</hask>, only that function has the type: 
<haskell>  <haskell>  
insertWith :: Ord k => (a > a > a) > k > a > Map k a > Map k a  insertWith :: Ord k => (a > a > a) > k > a > Map k a > Map k a  
Line 31:  Line 31:  
Here the update function receives the new value as well.  Here the update function receives the new value as well.  
[[User:TwanvlTwanvl]]  [[User:TwanvlTwanvl]]  
+  
+    
+  
+  Thanks for the tip! A whole new module for me to learn. My oh my... I do love the way Haskell type signatures almost tell you what the whole function does!  
+  
+  [[User:MathematicalOrchidMathematicalOrchid]] 19:27, 15 February 2007 (UTC)  
[[Category:Code]]  [[Category:Code]] 
Revision as of 19:27, 15 February 2007
I just wrote this 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)
As you can see (?!), this takes a list of key/value pairs and processes it as follows:
 The function is given a key to look for.
 If the key is found, a function is applied to the associated value.
 If the key is not found, it is inserted (at the correct place) with a specified 'default value'.
apply
apply
Ord
apply
Data.Map
When you are making excessive use of (key,value) pairs it is usually time to switch toData.Map
apply
Data.Map.insertWith
insertWith :: Ord k => (a > a > a) > k > a > Map k a > Map k a
Here the update function receives the new value as well. Twanvl

Thanks for the tip! A whole new module for me to learn. My oh my... I do love the way Haskell type signatures almost tell you what the whole function does!
MathematicalOrchid 19:27, 15 February 2007 (UTC)