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


I've read a good part of expert F # and working on building the actual application I am While debugging, I have become addicted to passing FIS commands in such a way so that some things can be clarified in the replay window:

  fsi.AddPrinter (Fun (x: myType) - & Gt; myType.ToString))  

I want to extend it to work with printf formatter, so I can type

 < Code> printf "% A" instanceOfMyType  

and control the output for a custom type. The book means that this can be done (P 93, "generic structural formatting can be extended to work with any user-defined data type, subject to the F # website"), but I How can I find a reference to actually accomplish this? Does anyone know how? Is this also possible?

Edit:

I should have included a sample sample, this is a record type with which I am working, e.g.

  type myType = {a: int} override m.ToString () = "hello" t = {a = 5} printfn "% A" printfn "% A" (box T)   

It seems that F # 2.0 has the right to do this The attribute is used in a manner that, for example:

  [& lt; In this example, the default  {a = 42;}  

Instead of code>, you will get the Hello 42 .

This works the same way for objects, records and union types. And although the pattern should be of format ( PreText and PostText is optional), it is actually more powerful < Code> ToString () to:

  1. PropertyName can be any type of property if this string is not present, then this structured formatting Such a tree gives an example of formatting a tree again.

  2. It can be a calculated property, so you can In essence, you can get ToString () , work for records and union type, though in a round instead:

      [ type myType = {a: int} override m.ToString () = "Hello" member m.AsString = m.ToString () // A property that calls < By the way, if you call  printfn "% O", then  ToString ()  will always be used (records) And also for Union types) will be played   Printfn "% A" . 


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -