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

前端 未结 3 737
臣服心动
臣服心动 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条回答
  •  别那么骄傲
    2021-01-14 08:54

    I think the answer by kvb is a great explanation of the problem - why is it difficult to pass printf like functions to other functions as parameter. While kvb gives a workaround that makes this possible, I think it is probably not very practical (because the use of interfaces makes it a bit complex).

    So, if you want to parameterize your output, I think it is easier to take System.IO.TextWriter as an argument and then use printf like function that prints the output to the specified TextWriter:

    let OutputStuff printer =
      Printf.fprintfn printer "Hi there!"
      Printf.fprintfn printer "The answer is: %d" 42
    
    OutputStuff System.Console.Out
    

    This way, you can still print to different outputs using the printf style formatting strings, but the code looks a lot simpler (alternatively, you could use Printf.kprintf and specify a printing function that takes string instead of using TextWriter).

    If you want to print to an in-memory string, that's easy too:

    let sb = System.Text.StringBuilder()
    OutputStuff (new System.IO.StringWriter(sb))
    sb.ToString()
    

    In general, TextWriter is a standard .NET abstraction for specifying printing output, so it is probably a good choice.

提交回复
热议问题