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

左心房为你撑大大i 提交于 2019-11-27 14:35:08

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

[<StructuredFormatDisplay("hello {a}")>]
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:

    [<StructuredFormatDisplay("{AsString}")>]
    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".

Hmm... I vaguely recall some changes to this, but I forget if they happened before or after the CTP (1.9.6.2).

In any case, on the CTP, I see that

type MyType() =
    override this.ToString() = "hi"
let x = new MyType()
let xs = Array.create 25 x
printfn "%A" x
printfn "%A" xs

when evaluated in the VFSI window does what I would want, and that

x;;
xs;;

also prints nicely. So, I guess I am unclear how this differs from what is desired?

If you override ToString method, that should do.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!