@@ -30,19 +30,24 @@ module Data.Map
3030 , union
3131 , unionWith
3232 , unions
33+ , isSubmap
3334 , size
3435 , mapWithKey
36+ , filterWithKey
37+ , filterKeys
38+ , filter
3539 ) where
3640
3741import Prelude
3842import Data.Eq (class Eq1 )
3943import Data.Foldable (foldl , foldMap , foldr , class Foldable )
4044import Data.List (List (..), (:), length , nub )
45+ import Data.List.Lazy as LL
4146import Data.Maybe (Maybe (..), maybe , isJust , fromMaybe )
4247import Data.Monoid (class Monoid )
4348import Data.Ord (class Ord1 )
4449import Data.Traversable (traverse , class Traversable )
45- import Data.Tuple (Tuple (Tuple), snd )
50+ import Data.Tuple (Tuple (Tuple), snd , uncurry )
4651import Data.Unfoldable (class Unfoldable , unfoldr )
4752import Partial.Unsafe (unsafePartial )
4853
@@ -461,6 +466,11 @@ union = unionWith const
461466unions :: forall k v f . Ord k => Foldable f => f (Map k v ) -> Map k v
462467unions = foldl union empty
463468
469+ -- | Test whether one map contains all of the keys and values contained in another map
470+ isSubmap :: forall k v . Ord k => Eq v => Map k v -> Map k v -> Boolean
471+ isSubmap m1 m2 = LL .all f $ (toUnfoldable m1 :: LL.List (Tuple k v ))
472+ where f (Tuple k v) = lookup k m2 == Just v
473+
464474-- | Calculate the number of key/value pairs in a map
465475size :: forall k v . Map k v -> Int
466476size = length <<< values
@@ -470,3 +480,19 @@ mapWithKey :: forall k v v'. (k -> v -> v') -> Map k v -> Map k v'
470480mapWithKey _ Leaf = Leaf
471481mapWithKey f (Two left k v right) = Two (mapWithKey f left) k (f k v) (mapWithKey f right)
472482mapWithKey f (Three left k1 v1 mid k2 v2 right) = Three (mapWithKey f left) k1 (f k1 v1) (mapWithKey f mid) k2 (f k2 v2) (mapWithKey f right)
483+
484+ -- | Filter out those key/value pairs of a map for which a predicate
485+ -- | fails to hold.
486+ filterWithKey :: forall k v . Ord k => (k -> v -> Boolean ) -> Map k v -> Map k v
487+ filterWithKey predicate =
488+ fromFoldable <<< LL .filter (uncurry predicate) <<< toUnfoldable
489+
490+ -- | Filter out those key/value pairs of a map for which a predicate
491+ -- | on the key fails to hold.
492+ filterKeys :: forall k . Ord k => (k -> Boolean ) -> Map k ~> Map k
493+ filterKeys predicate = filterWithKey $ const <<< predicate
494+
495+ -- | Filter out those key/value pairs of a map for which a predicate
496+ -- | on the value fails to hold.
497+ filter :: forall k v . Ord k => (v -> Boolean ) -> Map k v -> Map k v
498+ filter predicate = filterWithKey $ const predicate
0 commit comments