How do I print an entire list in F#?

2020-07-18 02:58发布

问题:

When I use Console.WriteLine to print a list, it defaults to only showing the first three elements. How do I get it to print the entire contents of the list?

回答1:

You can use the %A format specifier along with printf to get a 'beautified' list printout, but like Console.WriteLine (which calls .ToString()) on the object, it will not necessarily show all the elements. To get them all, iterate over the whole list. The code below shows a few different alternatives.

let smallList = [1; 2; 3; 4]
printfn "%A" smallList // often useful

let bigList = [1..200]
printfn "%A" bigList // pretty, but not all

printfn "Another way"
for x in bigList do 
    printf "%d " x
printfn ""

printfn "Yet another way"
bigList |> List.iter (printf "%d ")
printfn ""


回答2:

You can iterate over the it, using the List.iter function, and print each element:

let list = [1;2;3;4]
list |> List.iter (fun x -> printf "%d " x)

More info:

  • Lists in F# (MSDN)


回答3:

Here's simple alternative that uses String.Join:

open System

let xs = [1; 2; 3; 4]
let s = "[" + String.Join("; ", xs) + "]"
printfn "%A" s


标签: f#