Skip to content

Simple utility for COMPLETE pragmas #17

Open
@treeowl

Description

@treeowl

I dunno if it belongs here, but COMPLETE pragmas are a bit painful to write by hand for types with many constructors, especially when constructors can be added or removed from time to time. Using th-abstraction, it's easy to fix this. Without th-abstraction, I don't wanna.

import Language.Haskell.TH.Datatype (DatatypeInfo (..), ConstructorInfo(..), reifyDatatype)
import Language.Haskell.TH (Q, Dec, Name, pragCompleteD)
import Data.List ((\\))

-- | Produce a @COMPLETE@ pragma for a type with many constructors,
-- without having to list them all out.
--
-- @completeWithButWithout ''T ['P] ['C1, 'C2]@ produces a @COMPLETE@
-- pragma stating that pattern matching on the type @T@ is complete with
-- with the pattern @P@ and with all the constructors of @T@ other than
-- @C1@ and @C2@.
completeWithButWithout :: Name -> [Name] -> [Name] -> Q [Dec]
completeWithButWithout ty extra_patterns excl_constrs = do
  di <- reifyDatatype ty
  let constrs = map constructorName (datatypeCons di)
  (:[]) <$> pragCompleteD (extra_patterns ++ (constrs \\ excl_constrs))
                          (Just ty)

For truly enormous datatypes, (\\) could be swapped out in favor of something that uses the Ord Name instance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions