You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用Cabal运行的Haskell脚本中启用assert断言?

在Cabal脚本中启用断言(assert)

我需要在Cabal运行的Haskell脚本里使用assert功能。根据官方文档说明:

通常可通过编译器标志开启或关闭断言(对于GHC,默认开启断言,除非使用-O开启优化或指定-fignore-asserts选项)。断言关闭时,assert的第一个参数会被忽略,直接返回第二个参数的结果。

从执行输出能看到,当前编译使用了-O1优化,导致断言被关闭——我的脚本里assert (2 > 3)没有触发失败,反而输出了2。现在需要解决的是:如何在启用优化的情况下强制开启断言检查。

我的脚本内容

{- cabal:
build-depends: base
-}

-- cabal run debug.hs

import System.Environment
import Control.Exception (assert)

main :: IO ()
main = do
    let sum = assert (2 > 3) $ 1+ 1
    print sum

执行过程输出

PS C:\Users\<me>\Desktop\<...>\haskell> cabal run debug.hs
Warning: The package list for 'hackage.haskell.org' is 1096 days old.
Run 'cabal update' to get the latest list of available packages.
Resolving dependencies...
Build profile: -w ghc-8.10.2 -O1
In order, the following will be built (use -v for more details):
 - fake-package-0 (exe:script) (first run)
Configuring executable 'script' for fake-package-0..
Preprocessing executable 'script' for fake-package-0..
Building executable 'script' for fake-package-0..
[1 of 1] Compiling Main             ( Main.hs, C:\Users\<me>\AppData\Local\Temp\cabal-repl.-26728\dist-newstyle\build\x86_64-windows\ghc-8.10.2\fake-package-0\x\script\build\script\script-tmp\Main.o )
Linking C:\Users\<me>\AppData\Local\Temp\cabal-repl.-26728\dist-newstyle\build\x86_64-windows\ghc-8.10.2\fake-package-0\x\script\build\script\script.exe ...
2

解决方法

有两种方式可以在启用优化时强制开启断言:

方法1:命令行临时指定编译标志

运行脚本时通过--ghc-options参数传递-fno-ignore-asserts,强制GHC检查断言:

cabal run debug.hs --ghc-options="-fno-ignore-asserts"

方法2:在脚本的Cabal配置中永久添加标志

修改脚本顶部的Cabal注释块,加入ghc-options配置,这样每次运行都会自动启用断言:

{- cabal:
build-depends: base
ghc-options: -fno-ignore-asserts
-}

验证效果

修改后再次运行脚本,assert (2 > 3)会触发断言失败,抛出Assertion failed异常,而不是输出2,说明断言已正常启用。

内容的提问来源于stack exchange,提问作者peer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 05:45:25