使用 GHC Haskell 进行编译时断言?
来自 C++,我习惯于能够构建简单形式的编译时断言,如果通过使用模板元未满足某些简单条件(例如,通过简单的代数表达式),我可以在编译期间发出警告或错误-programming 和/或 cpp(1)
例如,如果我想确保我的程序仅在 Int
至少具有一定的值时才编译minBound
/maxBound
范围,或者,如果从 Int64
到 Int
的无损(如可逆)转换当前编译目标是可能的。这可以通过某些 GHC Haskell 扩展实现吗?我的第一个猜测是使用 TH。是否还有其他 GHC 设施可用于此目的?
Coming from C++, I'm used to be able to build simple forms of compile-time assertions, where I could emit warnings or errors during compilation if some simple conditions (e.g. over simple algebraic expressions) weren't met via use of template meta-programming and/or cpp(1)
For instance, if I wanted to make sure my program compiles only when Int
has at least a certain minBound
/maxBound
range or alternatively, if a loss-free (as in reversible) conversion from Int64
to Int
is possible with the current compilation target. Is this possible with some GHC Haskell extension? My first guess would have been to use TH. Are there other GHC facilities that could be exploited to this end?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
且稍微简化的版本:
以下是 Anthony 的示例的通用 :
Here's a generalized and slightly simplified version of Anthony's example:
Usage:
使用 TH 来实现这一点并不算太糟糕。下面是一个模块,它将所需的断言定义为残留声明的一部分:
使用断言涉及一个顶级声明,该声明除了断言之外不用于任何其他用途:
Using TH for this isn't too bad. Here is a module that defines the desired assertion as part of a vestigial declaration:
Using the assertion involves a top-level declaration that isn't used for anything other than the assertion: