OCaml:使用消息进行断言 [英] OCaml: assert with the message

查看:98
本文介绍了OCaml:使用消息进行断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个问题:P我不太确定是否应该在此处还是在OCaml邮件列表中发布它,但我会先尝试.

Another question again :P I'm not too sure whether I should post it here or on the OCaml mailing list, but I try SO first.

我喜欢断言语句.但是,我发现错误消息几乎没有用,而没有其他消息(XXX行断言— —很好,但是实际上出了什么问题?). 我认为断言的好例子是pythonic assert x > 0, "X must be greater than zero for the algorithm X to work",而不好的例子是类似C的assert(x>0).

I like assert statements. However, I find the error messages close to useless without an additional message (assertion violation at line XXX --- well great, but what actually went wrong?). I think the good example of an assertion is a pythonic assert x > 0, "X must be greater than zero for the algorithm X to work" and a bad example is C-like assert(x>0).

我很失望地得知无法将错误消息附加到OCaml =( 我的选择是:

I was quite disappointed to learn that there is no way to attach an error message to an assertion in OCaml =( My options are:

  • 编写一个自定义函数,例如vassert =>,但我不会获得魔术行号,而魔术行号只能通过assert关键字来实现
  • 使用failwith,但是它更加冗长,而且我认为还存在与自定义函数相同的问题.
  • 使用OUnit中的函数,但我不想引入不需要的依赖项.
  • Write a custom function, say vassert => but I won't get the magic line numbers which are only possible with the assert keyword
  • Use failwith, but it is considerably more verbose, and I think suffers from the same problem as a custom function.
  • Use functions from OUnit, but I don't want to introduce unneeded dependency.

其他人也有同样的问题吗?人们使用什么?

Does anyone else have the same problem? What do people use?

推荐答案

有点乏味,但效果很好:

A little bit tedious but works fine:

 assert (if not cond then print_endline "your message"; cond)

这篇关于OCaml:使用消息进行断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆