9

I am writing a F# program which parses a string into a AST type which is a discriminated union.

When I use fsi (on Mono + Mac OS X) to run my code, the AST is printed out in a nice format. But when I use printfn "%s" <| ast.ToString() I get something like FSI_0002.Absyn+clazz. Writing a ToString method for all the discriminated union types would be a big chore.

How do I make the value print the way fsi does it?

Binil Thomas
  • 13,450
  • 10
  • 53
  • 68
  • possible duplicate of https://stackoverflow.com/questions/1259039/what-is-the-enum-getname-equivalent-for-f-union-member – knocte Jan 10 '17 at 03:15

3 Answers3

10

Have you tried printfn "%A" ast? The %A specifier takes into consideration the StructuredFormatDisplayAttribute[MSDN], if present.

Daniel
  • 46,089
  • 10
  • 89
  • 172
2

To convert a discriminated union into a string, you should use sprintf "%A" ast instead of ast.ToString().

If you want Enum.GetName, you can use Microsoft.FSharp.Reflection namespace. See What is the Enum.GetName equivalent for F# union member?.

Community
  • 1
  • 1
Kwang Yul Seo
  • 711
  • 1
  • 7
  • 14
1

In addition to Daniel's comment, here is a good blog article explaining how to format it in whatever way you'd wish:

http://blogs.msdn.com/b/dsyme/archive/2010/01/08/some-tips-and-tricks-for-formatting-data-in-f-interactive-and-a-in-sprintf-printf-fprintf.aspx (web.archive.org)

Ramon Snir
  • 7,250
  • 3
  • 40
  • 58
  • 1
    This link is archived here: https://web.archive.org/web/20151011213338/http://blogs.msdn.com/b/dsyme/archive/2010/01/08/some-tips-and-tricks-for-formatting-data-in-f-interactive-and-a-in-sprintf-printf-fprintf.aspx – rfreytag Nov 30 '20 at 19:36
  • @rfreytag thanks, updated link! – Ramon Snir Nov 30 '20 at 19:54