I\'d like to make a function in F# that accepts a printf-style function as an argument, and uses that argument to output data. Usage would be something like the following:>
The problem is that when you say (output : Printf.TextWriterFormat<'a> -> 'a)
, that means "there is some 'a
for which output takes a Printf.TextWriterFormat<'a>
to an 'a
". Instead, what you want to say is "for all 'a
output can take a Printf.TextWriterFormat<'a>
and return a 'a
.
This is a bit ugly to express in F#, but the way to do it is with a type with a generic method:
type IPrinter =
abstract Print : Printf.TextWriterFormat<'a> -> 'a
let OutputStuff (output : IPrinter) =
output.Print "Header"
output.Print "Data: %d" 42
OutputStuff { new IPrinter with member this.Print(s) = printfn s }