How do I print an entire list in F#?

白昼怎懂夜的黑 提交于 2019-12-06 04:11:40

问题


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


来源:https://stackoverflow.com/questions/1656200/how-do-i-print-an-entire-list-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!