开发者

How do I print an entire list in F#?

When I use Console.Writ开发者_StackOverfloweLine 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?


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


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)


Here's simple alternative that uses String.Join:

open System

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜