【发布时间】:2019-07-14 20:20:56
【问题描述】:
我使用准引用器在编译时创建我的智能构造数据类型。这看起来像:
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,因为当我这样做时:
f :: NonEmptyText -> Bool
f [compileNonEmptyText|test|] = True
f _ = False
一切都与第一个语句匹配。
【问题讨论】:
标签: haskell template-haskell quasiquotes