Printf with automatic '\n'

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?

Just replace ^ (string concatenation) by ^^ (format string concatenation): let warn fmt = Printf.eprintf (fmt ^^ "\n").

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

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

Thanks a lot!

PS: Where did you guys learn all these nifty things?

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