dromas
March 12, 2020, 11:01am
1
Hello,
I’d like to have a printf-like function, that prints a newline after each message.
Here is one of my attempts (which doesn’t even compile):
let warn fmt = Printf.eprintf (fmt ^ "\n")
let () =
let fname = "abc" in
let lnum = 123 in
warn "%s:%d: hello world" fname lnum
Any suggestions how to accomplish this?
nojb
March 12, 2020, 11:35am
2
Just replace ^
(string concatenation) by ^^
(format string concatenation): let warn fmt = Printf.eprintf (fmt ^^ "\n")
.
3 Likes
dromas
March 12, 2020, 2:09pm
3
Thanks a lot! (I don’t even dare to tell you how much time I spent trying to implement this).
Is it possible to also exit
the program after printing the message?
This makes it exit, but doesn’t print anything:
let fail fmt = Printf.eprintf (fmt ^^ "\n"); exit 1
let () =
fail "giving up after %d errors" 123
(I’m aware of exit
preventing the partial function application here, but don’t know how fix it).
Drup
March 12, 2020, 2:24pm
4
You should use kprintf
for these cases:
let fail fmt = Printf.kfprintf (fun _ -> exit 1) stderr (fmt ^^ "\n%!")
Similarly, for Format
(although no need to play with format strings):
let fail fmt =
Format.kfprintf
(fun fmt -> Format.pp_print_flush fmt (); exit 1)
Format.err_formatter fmt
2 Likes
dromas
March 12, 2020, 2:54pm
5
Thanks a lot!
PS: Where did you guys learn all these nifty things?
1 Like
jhw
March 12, 2020, 6:07pm
6
Lost in the mists of history? Seems like this stuff has been in OCaml since forever. (It was one of the first things I noticed when I was learning the language back in 2001.)