gpt4 book ai didi

exception - 在 SML 中,如何断言特定异常被抛出?

转载 作者:行者123 更新时间:2023-11-28 19:45:49 25 4
gpt4 key购买 nike

我没有努力实际克隆 JUnit 或其他东西,而是将一些实用函数放在一起以帮助测试一些 SML 代码。我知道 QCheck,但它也不能做这件事,而且通常不是我想要的。 (但如果您知道另一个 SML 自动化测试框架,请大声说出来。)

我希望能够断言某个函数会抛出异常,例如,给定一个函数

fun broken x = raise Fail

我希望能够写出类似的东西

throws ("ERROR: function is not broken enough!", fn () => broken 1, Fail)

如果给定的函数没有引发预期的异常,让它抛出错误。

我试着用 (string * exn * (unit -> unit)) -> unit 写一个 throws 函数,像这样:

  fun throws (msg, e, func) = func ()
handle e' => if e = e'
then ()
else raise ERROR (SOME msg)

但这会产生一堆编译时错误,显然是因为 ML没有定义异常(exception)的平等:

sexp-tests.sml:54.31-57.49 Error: types of rules don't agree [equality type required]
earlier rule(s): ''Z -> unit
this rule: exn -> 'Y
in rule:
exn => raise exn
sexp-tests.sml:54.31-57.49 Error: handler domain is not exn [equality type required]
handler domain: ''Z
in expression:
func ()
handle
e' => if e = e' then () else raise (ERROR <exp>)
| exn => raise exn

作为一种解决方法,我怀疑我可以重用我拥有的现有 assert 函数:

assert ((broken 1; false) handle Fail => true | _ => false)

但这需要更多思考和输入。

那么,有什么方法可以用 SML 编写 throws 函数吗?

最佳答案

以下函数应该有效:

exception ERROR of string option;

fun throwError msg = raise ERROR (SOME msg);

fun throws (msg, func, e) =
(func (); throwError msg) handle e' =>
if exnName e = exnName e'
then ()
else raise throwError msg

这使用函数 exnName ,它将异常的名称作为字符串获取,并将其用于比较。

更重要的是,它还处理完全没有抛出异常的情况,并给出错误。

或者,如果您只需要一个 bool 值,指示是否抛出异常,您可以使用:

fun bthrows (func, e) = (func (); false) handle e' => exnName e = exnName e'

请注意,对于失败的情况,您实际上必须创建一个失败异常的实例,例如:

throws ("ERROR: Oh no!", fn () => test 5, Fail "")

或者,对于更清晰的一般情况,您可以使用异常的名称:

fun throws (msg, func, e) =
(func (); throwError msg) handle e' =>
if e = exnName e'
then ()
else raise throwError msg

fun bthrows (func, e) = (func (); false) handle e' => e = exnName e'

然后像这样使用它:

throws ("ERROR: Oh no!", fn () => test 5, "Fail")

关于exception - 在 SML 中,如何断言特定异常被抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5987444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com