OCaml: assert with the message

2019-07-04 04:51发布

问题:

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.



标签: ocaml