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

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

Leave a Comment