Printing F# discriminated union

眉间皱痕 提交于 2019-11-30 04:04:49

问题


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?


回答1:


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




回答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?.




回答3:


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



来源:https://stackoverflow.com/questions/7452074/printing-f-discriminated-union

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