TemplateHaskell
, UnicodeSyntax
#-}
--- |FIXME: doc
+-- |Doesn't anyone know why these instances can't be derived using
+-- GeneralizedNewtypeDeriving? I think its limitation isn't reasonable
+-- at all...
module Data.Collections.Newtype.TH
( derive
)
type Deriver = Q Cxt → Q Type → Q Exp → Q Exp → Q Dec
--- |FIXME: doc
+-- |Automatic newtype instance deriver for type classes defined by the
+-- collections-api package.
+--
+-- @
+-- {-\# LANGUAGE TemplateHaskell \#-}
+-- module Foo (T) where
+-- import "Data.Collections"
+-- import "Data.Collections.BaseInstances" ()
+-- import qualified Data.Collections.Newtype.TH as C
+-- import qualified "Data.Map" as M
+--
+-- newtype T = T (M.Map 'Int' 'Bool')
+--
+-- C.derive [d| instance 'Unfoldable' T ('Int', 'Bool')
+-- instance 'Foldable' T ('Int', 'Bool')
+-- instance 'Indexed' T 'Int' 'Bool'
+-- ...
+-- |]
+-- @
+--
+-- This function can derive the following instances:
+--
+-- * 'Unfoldable'
+--
+-- * 'Foldable'
+--
+-- * 'Collection'
+--
+-- * 'Indexed'
+--
+-- * 'Map'
+--
+-- * 'Set'
+--
+-- * 'SortingCollection'
+--
derive ∷ Q [Dec] → Q [Dec]
derive = (concat <$>) ∘ (mapM go =≪)
where
= return (wrapperTy, deriveFoldable)
| classTy ≡ ''Collection
= return (wrapperTy, deriveCollection)
+ | classTy ≡ ''Set
+ = return (wrapperTy, deriveSet)
| classTy ≡ ''SortingCollection
= return (wrapperTy, deriveSortingCollection)
inspectInstance (AppT (AppT (AppT (ConT classTy) wrapperTy) _) _)
| otherwise
= fail $ "deriveMap: unknown method: " ⧺ pprint name
+deriveSet ∷ Q Cxt → Q Type → Q Exp → Q Exp → Q Dec
+deriveSet c ty _ _
+ = do names ← methodNames ''Set
+ instanceD c ty $ concatMap (pointfreeMethod exp) names
+ where
+ exp ∷ Name → Q Exp
+ exp name
+ | name ≡ 'haddock_candy
+ = [| haddock_candy |]
+ | otherwise
+ = fail $ "deriveSet: unknown method: " ⧺ pprint name
+
deriveSortingCollection ∷ Q Cxt → Q Type → Q Exp → Q Exp → Q Dec
deriveSortingCollection c ty wrap unwrap
= do names ← methodNames ''SortingCollection