简体   繁体   English

打印 F# 可区分联合

[英]Printing F# discriminated union

I am writing a F# program which parses a string into a AST type which is a discriminated union.我正在编写一个 F# 程序,它将一个字符串解析为一个 AST 类型,它是一个可区分的联合。

When I use fsi (on Mono + Mac OS X) to run my code, the AST is printed out in a nice format.当我使用fsi (在 Mono + Mac OS X 上)运行我的代码时,AST 以一种很好的格式打印出来。 But when I use printfn "%s" <| ast.ToString()但是当我使用printfn "%s" <| ast.ToString() printfn "%s" <| ast.ToString() I get something like FSI_0002.Absyn+clazz . printfn "%s" <| ast.ToString()我得到类似FSI_0002.Absyn+clazz东西。 Writing a ToString method for all the discriminated union types would be a big chore.为所有可区分的联合类型编写ToString方法将是一项繁重的工作。

How do I make the value print the way fsi does it?如何按照fsi的方式打印值?

Have you tried printfn "%A" ast ?你试过printfn "%A" ast吗? The %A specifier takes into consideration the StructuredFormatDisplayAttribute [MSDN] , if present. %A说明符考虑StructuredFormatDisplayAttribute [MSDN] (如果存在)。

To convert a discriminated union into a string, you should use sprintf "%A" ast instead of ast.ToString().要将可区分联合转换为字符串,您应该使用sprintf "%A" ast而不是 ast.ToString()。

If you want Enum.GetName , you can use Microsoft.FSharp.Reflection namespace.如果你想要Enum.GetName ,你可以使用Microsoft.FSharp.Reflection命名空间。 See What is the Enum.GetName equivalent for F# union member?请参阅F# 联合成员的 Enum.GetName 等效项是什么? . .

In addition to Daniel's comment, here is a good blog article explaining how to format it in whatever way you'd wish:除了 Daniel 的评论之外,这里还有一篇很好的博客文章,解释了如何以您希望的任何方式对其进行格式化:

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) 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM