F#: how to print full list (Console.WriteLine() prints only first three elements)

Nike picture Nike · Mar 25, 2010 · Viewed 27.8k times · Source

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; ... ]

Answer

Tomas Petricek picture Tomas Petricek · Mar 25, 2010

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; ... ]

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)

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