Skip to content

Instantly share code, notes, and snippets.

@frasertweedale
Created February 27, 2019 03:07
Show Gist options
  • Save frasertweedale/dc3d5834d93b52819d3b82400e77a867 to your computer and use it in GitHub Desktop.
Save frasertweedale/dc3d5834d93b52819d3b82400e77a867 to your computer and use it in GitHub Desktop.
union maps, reject and collect duplicate keys
module Example where
import Data.Map
import Data.Validation
import Data.List.NonEmpty (NonEmpty((:|)))
-- | Merge maps rejecting duplicate keys, which are collected in the 'Failure' value
--
-- >>> awsm (fromList [('a', 1)]) (fromList [('b', 2)])
-- Success (fromList [('a',1),('b',2)])
-- >>> awsm (fromList [('a', 1)]) (fromList [('b', 2), ('a', 3)])
-- Failure ('a' :| "")
-- >>> awsm (fromList [('a', 1), ('b', 4)]) (fromList [('b', 2), ('a', 3)])
-- Failure ('a' :| "b")
--
awsm :: Ord k => Map k v -> Map k v -> Validation (NonEmpty k) (Map k v)
awsm m1 m2 = sequenceA $ unionWithKey (\k _ _ -> Failure (k:|[])) (Success <$> m1) (Success <$> m2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment