How to pass a printf-style function to another function in F#

前端 未结 3 738
臣服心动
臣服心动 2021-01-14 08:36

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:

3条回答
  •  -上瘾入骨i
    2021-01-14 08:59

    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 }
    

提交回复
热议问题