{-# LANGUAGE TemplateHaskell #-}
module StaticAssert (staticAssert) where
import Control.Monad (unless)
import Language.Haskell.TH (report)
staticAssert cond mesg = do
unless cond $ report True $ "Compile time assertion failed: " ++ mesg
return [] -- No need to make a dummy declaration
{-# LANGUAGE TemplateHaskell #-}
module CompileTimeWarning where
import Control.Monad (unless)
import Data.Int (Int64)
import Language.Haskell.TH
assertInt = let test = fromIntegral (maxBound::Int) == (maxBound::Int64)
in do unless test $ report True "Int is not safe!"
n <- newName "assertion"
e <- fmap NormalB [|()|]
return $ [FunD n [Clause [] e []]]
使用断言涉及顶级声明,该声明不用于断言以外的任何其他内容:
{-# LANGUAGE TemplateHaskell #-}
import CompileTimeWarning
$(assertInt)
2 回答
这是Anthony's example的通用和略微简化版本:
用法:
使用TH来做到这一点并不算太糟糕 . 这是一个模块,它定义了所需的断言作为残留声明的一部分:
使用断言涉及顶级声明,该声明不用于断言以外的任何其他内容: