--- |@'serializeExtMap' extMap moduleName variableName@ generates a
--- Haskell source code which contains the following things:
---
--- * A definition of module named @moduleName@.
---
--- * @variableName ∷ 'ExtMap'@ whose content is a serialization of
--- @extMap@.
---
--- The module "Network.HTTP.Lucu.MIMEType.DefaultExtensionMap" is
--- surely generated using this function.
-serializeExtMap ∷ ExtMap → String → String → String
-serializeExtMap extMap moduleName variableName
- = let hsModule = HsModule (⊥) modName (Just exports) imports decls
- modName = Module moduleName
- exports = [HsEVar (UnQual (HsIdent variableName))]
- imports = [ HsImportDecl (⊥) (Module "Network.HTTP.Lucu.MIMEType") False Nothing Nothing
- , HsImportDecl (⊥) (Module "Network.HTTP.Lucu.MIMEType.Guess") False Nothing Nothing
- , HsImportDecl (⊥) (Module "Data.Ascii") True (Just (Module "A")) Nothing
- , HsImportDecl (⊥) (Module "Data.Map") True (Just (Module "M")) Nothing
- , HsImportDecl (⊥) (Module "Data.Text") True (Just (Module "T")) Nothing
- ]
- decls = [ HsTypeSig (⊥) [HsIdent variableName]
- (HsQualType []
- (HsTyCon (UnQual (HsIdent "ExtMap"))))
- , HsFunBind [HsMatch (⊥) (HsIdent variableName)
- [] (HsUnGuardedRhs extMapExp) []]
- ]
- extMapExp = HsApp (HsVar (Qual (Module "M") (HsIdent "fromList"))) (HsList records)
- comment = "{- !!! WARNING !!!\n"
- ++ " This file is automatically generated.\n"
- ++ " DO NOT EDIT BY HAND OR YOU WILL REGRET -}\n\n"
- in
- comment ++ prettyPrint hsModule ++ "\n"
- where
- records ∷ [HsExp]
- records = map record $ M.assocs extMap
+ go ∷ Ord k ⇒ Map k v → [(k, v)] → Either (k, v, v) (Map k v)
+ go m [] = Right m
+ go m ((k, v):xs)
+ = case M.insertLookupWithKey' f k v m of
+ (Nothing, m') → go m' xs
+ (Just v0, _ ) → Left (k, v0, v)