我使用准引用器在编译时创建我的智能构造数据类型。这看起来像:
import qualified Data.Text as T
import Language.Haskell.TH.Quote (QuasiQuoter(..))
import Language.Haskell.TH (Q, Exp, Pat(..), Lit(..))
import Language.Haskell.TH.Syntax (Lift(..))
import qualified Language.Haskell.TH.Syntax as TH
import Instances.TH.Lift () -- th-lift-instances package
newtype NonEmptyText = NonEmptyText Text
textIsWhitespace :: Text -> Bool
textIsWhitespace = T.all (== ' ')
mkNonEmptyText :: Text -> Maybe NonEmptyText
mkNonEmptyText t = if textIsWhitespace t then Nothing else (Just (NonEmptyText t))
compileNonEmptyText :: QuasiQuoter
compileNonEmptyText = QuasiQuoter
{ quoteExp = compileNonEmptyText'
, quotePat = error "NonEmptyText is not supported as a pattern"
, quoteDec = error "NonEmptyText is not supported at top-level"
, quoteType = error "NonEmptyText is not supported as a type"
}
where
compileNonEmptyText' :: String -> Q Exp
compileNonEmptyText' s = case mkNonEmptyText (pack s) of
Nothing -> fail $ "Invalid NonEmptyText: " ++ s
Just txt -> [| txt |]
(如有必要,我可以提供一个独立的工作示例——我只是从一个更大的代码库中提取了这个示例)
本质上,只需Lift
为我的新类型派生,我就可以将数据类型放在表达式准引用[| txt |]
器中以实现quoteExp
.
但我遇到了麻烦quotePat
。如果我这样做:
Just txt -> [p| txt |]
然后我收到第一个 txt 未使用的警告,第二个遮住了第一个。我很确定该模式只是创建一个新名称txt
,而不是txt
像 quasi quoter 表达式那样在范围内拼接,因为当我这样做时:
f :: NonEmptyText -> Bool
f [compileNonEmptyText|test|] = True
f _ = False
一切都符合第一个陈述。