How do I create an F# function with a printf style logging argument?
f#, printf
Solution
Unfortunately, you cannot pass functions like `printf` as parameters to other functions and then use them with multiple different arguments. The problem is that `printf` is a generic function of type `Printf.TextWriterFormat<'a> -> 'a`. The actual type substituted for the type parameter `'a` is some function type that is different each time you use `printf` (e.g. `'a == string -> unit` for `"%s"` etc).
In F#, you cannot have parameter of a function that is itself a generic function. The generic function will have to be some global function, but you can parameterize it by the function that actually does something with the string. This is essentially what `kprintf` does, but you can name your function better:
let logPrintf logger format =
Printf.kprintf logger format
An example of function parameterized by the logger would be:
let testLogger (source:seq<'a>) logger =
logPrintf logger "Testing..."
let length = source |> Seq.length
logPrintf logger "Got a length of %d" length
let logger = printfn "%A: %s" System.DateTime.Now
testLogger [1; 2; 3] logger
Problem
I'm trying to create a framework to do some processing of files and data. The one area I'm struggling with is how to provide a logging function to the framework, allowing the framework to report messages without having any knowledge of the logging in use. ``` let testLogger (source:seq<'a>) logger = logger "Testing..." let length = source |> Seq.length logger "Got a length of %d" length let logger format = Printf.kprintf (printfn "%A: %s" System.DateTime.Now) format testLogger [1; 2; 3] logger ``` Ideally I want this code to work, but I can't work out how to pass the logger function in.