How do I customize output of a custom type using printf?

后端 未结 3 499
难免孤独
难免孤独 2020-12-03 10:01

I\'ve read through a good chunk of Expert F# and am working on building an actual application. While debugging, I\'ve grown accustomed to passing fsi commands like

3条回答
  •  [愿得一人]
    2020-12-03 10:19

    It looks like the Right Way to do this in F# 2.0 is by using the StructuredFormatDisplay attribute, for example:

    []
    type myType = {a: int}
    

    In this example, instead of the default {a = 42;}, you would get hello 42.

    This works the same way for object, record, and union types. And although the pattern must be of the format "PreText {PropertyName} PostText" (PreText and PostText being optional), this is actually more powerful than ToString() because:

    1. PropertyName can be a property of any type. If it is not a string, then it will also be subject to structured formatting. Don Syme's blog gives an example of recursively formatting a tree in this way.

    2. It may be a calculated property. So you could actually get ToString() to work for record and union types, though in a rather round-about way:

      []
      type myType = 
          {a: int}
          override m.ToString() = "hello"
          member m.AsString = m.ToString()  // a property that calls a method
      

    By the way, ToString() will always be used (even for record and union types) if you call printfn "%O" instead of printfn "%A".

提交回复
热议问题