[英]Compile-time assertions with GHC Haskell?
来自 C++,我习惯于构建简单的 forms 编译时断言,如果通过使用模板元未满足某些简单条件(例如,通过简单的代数表达式),我可以在编译期间发出警告或错误- 编程和/或cpp(1)
例如,如果我想确保我的程序仅在Int
至少具有某个minBound
/ maxBound
范围时编译,或者,如果当前编译目标可以从Int64
到Int
进行无损失(如可逆)转换。 这可能与某些 GHC Haskell 扩展有关吗? 我的第一个猜测是使用 TH。 是否有其他 GHC 设施可用于此目的?
这是Anthony 示例的通用且略微简化的版本:
{-# 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 #-}
import StaticAssert
$(staticAssert False "Not enough waffles")
为此使用 TH 还不错。 这是一个模块,它将所需的断言定义为残留声明的一部分:
{-# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.