F#:如何打印完整列表(Console.WriteLine()仅打印前三个元素) [英] F#: how to print full list (Console.WriteLine() prints only first three elements)
问题描述
是否可以不使用循环打印完整列表? 我试过了:
Is it possible to print full list without using cycle? I tried:
Console.WriteLine([1;2;3;4;5])
,它只打印三个前元素:
and it prints only three first elements:
[1;2;3; ... ]
推荐答案
如果要使用内置的F#格式化引擎(并避免自己实现同一功能),则可以使用诸如printfn
的F#打印功能. .您可以为其指定格式说明符,以打印整个列表(使用F#格式)或仅打印前几个元素(调用ToString
时会发生这种情况):
If you want to use the built-in F# formatting engine (and avoid implementing the same thing yourself), you can use F# printing functions such as printfn
. You can give it a format specifier to print an entire list (using F# formatting) or print just a first few elements (which happens when you call ToString
):
> printfn "%A" [ 1 .. 5 ];; // Full list using F# formatting
[1; 2; 3; 4; 5]
> printfn "%O" [ 1 .. 5 ];; // Using ToString (same as WriteLine)
[1; 2; 3; ... ]
如果出于某种原因要使用Console.WriteLine
(或其他.NET方法),也可以使用sprintf
,其行为与printf
类似,但返回格式化的字符串作为结果:
If you want to use Console.WriteLine
(or other .NET method) for some reason, you can also use sprintf
which behaves similarly to printf
, but returns the formatted string as the result:
Console.WriteLine(sprintf "%A" list)
使用printf
或sprintf
的好处是它还会自动处理其他F#类型(例如,如果您有一个包含元组,已区分联合或记录的列表).
The benefit of using printf
or sprintf
is that it also automatically deals with other F# types (for example if you have a list containing tuples, discriminated unions or records).
这篇关于F#:如何打印完整列表(Console.WriteLine()仅打印前三个元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!