on master help sign in
Add Dict.{filter(WithKey),partition(WithKey)}

Not quite working - need to work out why the compiler thinks these new functions are not in scope.

commit36d549fe26bcbc00d7e07f105b96d6a7680ec0e3 authorHarry Garrood <harry@garrood.me> dateTue 15 Apr 2014, 11:53 (13 years ago) parent277fabe
1 file changed+30−6
libraries/Dict.elm+30−6
libraries/Dict.elm+30−6
@@ -1,6 +1,8 @@
11module Dict (empty,singleton,insert,update
22 ,lookup,findWithDefault
33 ,remove,member
4+ ,filter,filterWithKey
5+ ,partition,partitionWithKey
46 ,foldl,foldr,map
57 ,union,intersect,diff
68 ,keys,values
@@ -327,9 +329,7 @@ union t1 t2 = foldl insert t2 t1
327329{-| Keep a key-value pair when its key appears in the second dictionary.
328330Preference is given to values in the first dictionary. -}
329331intersect : Dict comparable v -> Dict comparable v -> Dict comparable v
330−intersect t1 t2 =
331− let combine k v t = if k `member` t2 then insert k v t else t
332− in foldl combine empty t1
332+intersect t1 t2 = filterWithKey (\k _ -> k `member` t2) t1
333333
334334{-| Keep a key-value pair when its key does not appear in the second dictionary.
335335Preference is given to the first dictionary. -}
@@ -354,6 +354,30 @@ fromList assocs = List.foldl (\(k,v) d -> insert k v d) empty assocs
354354
355355{-| Keep only key-value pairs where the value satisfies a predicate. -}
356356filter : (v -> Bool) -> Dict comparable v -> Dict comparable v
357−filter p =
358− let add k v t = if p v then insert k v t else t
359− in foldl combine empty
357+filter p = filterWithKey (\_ v -> p v)
358+
359+{-| Keep only key-value pairs which satisfy a predicate. -}
360+filterWithKey : (comparable -> v -> Bool)
361+ -> Dict comparable v
362+ -> Dict comparable v
363+filterWithKey p =
364+ let add k v t = if p k v then insert k v t else t
365+ in foldl add empty
366+
367+{-| Partition the Dict according to a predicate. The first Dict contains all
368+values which satisfy a predicate; the second contains the rest. -}
369+partition : (v -> Bool)
370+ -> Dict comparable v
371+ -> (Dict comparable v, Dict comparable v)
372+partition p = partitionWithKey (\_ v -> p v)
373+
374+{-| Partition the Dict according to a predicate. The first Dict contains all
375+key-value pairs which satisfy a predicate; the second contains the rest. -}
376+partitionWithKey : (comparable -> v -> Bool)
377+ -> Dict comparable v
378+ -> (Dict comparable v, Dict comparable v)
379+partitionWithKey p =
380+ let add k v (t1, t2) = if p k v
381+ then (insert k v t1, t2)
382+ else (t1, insert k v t2)
383+ in foldl add (empty, empty)