Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write custom version of F# printfn that takes variable number of arguments?

Tags:

printf

f#

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.

like image 447
Vagif Abilov Avatar asked Mar 06 '23 13:03

Vagif Abilov


1 Answers

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
like image 195
Mankarse Avatar answered Apr 25 '23 18:04

Mankarse