How to define printfn equivalent in F#
f#, f#-interactive
Solution
You can use the `kprintf` function, which formats a string using the standard syntax, but then calls a (lambda) function you specify to print the formatted string.
For example, the following prints the string if `debug` is set and otherwise does nothing:
let myprintf fmt = Printf.kprintf (fun str ->
// Output the formatted string if 'debug', otherwise do nothing
if debug then printfn "%s" str) fmt
Problem
Since I do research with F# (in particular, using F# interactive), I'd like to have switchable "print-when-in-debug" function. I can do ``` let dprintfn = printfn ``` F# interactive says ``` val dprintfn : (Printf.TextWriterFormat<'a> -> 'a) ``` and I can use ``` dprintfn "myval1 = %d, other val = %A" a b ``` whenever I want in my scripts. Now I'd like to define `dprintfn` differently, so that it would ignore all its arguments yet being syntax-compatible with `printfn`. How? The closest (yet non-working) variant I have in mind is: ``` let dprintfn (arg: (Printf.TextWriterFormat<'a> -> 'a)) = () ``` but it the following doesn't compile then `dprintfn "%A" "Hello"`, resulting in `error FS0003: This value is not a function and cannot be applied`. P.S. I currently use an alias for `Debug.WriteLine(...)` as work-around, but the question is still interesting for understading F#'s type system.