OCaml: assert with the message

做~自己de王妃 提交于 2019-12-13 14:23:37

问题


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.

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).

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

  • 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?


回答1:


A little bit tedious but works fine:

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



回答2:


For me, the simpler way to dot that is to compile with the -g option and then add OCAMLRUNPARAM=b to the environment. This way you can write your own vassert, and you will get the whole stack trace that produced the call.

Of course, this is a result of my personal workflow were I consider assert as a debugging only tool that should never get seen by the final user.



来源:https://stackoverflow.com/questions/22561566/ocaml-assert-with-the-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!