I want to write an extended version of F# printfn function that prints current time in addition to text. Something like this:
let printimefn fmt =
let time = DateTime.Now
let strtime = sprintf "%02d:%02d:%02d" time.Hour time.Minute time.Second
printfn "%s %A" strtime fmt
Unfortunately this doesn't work as expected. The "fmt" argument loses its type Printf.TextWriterFormat<'T>.
I can force its type by using type annotation:
let printimefn (fmt : Printf.TextWriterFormat<'T>) =
let time = DateTime.Now
let strtime = sprintf "%02d:%02d:%02d" time.Hour time.Minute time.Second
printfn "%s %A" strtime fmt
But then the result of printimefn becomes unit, and not 'T. So it still doesn't work. I wonder what is the right way of to write a custom printfn function.
This can be done with Printf.ksprintf
let printimefn fmt =
let time = DateTime.Now
Printf.ksprintf (
fun s ->
printfn "%02d:%02d:%02d %s" time.Hour time.Minute time.Second s)
fmt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With