F#:如何打印完整列表(Console.WriteLine()只打印前三个元素)

Nik*_*ike 33 f# list

是否可以不使用循环打印完整列表?我试过了:

Console.WriteLine([1;2;3;4;5])
Run Code Online (Sandbox Code Playgroud)

它只打印三个第一个元素:

[1;2;3; ... ]
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 53

如果你想使用内置的F#格式化引擎(并避免自己实现相同的东西),你可以使用F#打印功能,如printfn.你可以给它一个格式说明符来打印整个列表(使用F#格式化)或只打印前几个元素(当你调用时会发生这种情况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; ... ]
Run Code Online (Sandbox Code Playgroud)

如果Console.WriteLine由于某种原因想要使用(或其他.NET方法),您也可以使用sprintf与...类似的行为printf,但返回格式化的字符串作为结果:

Console.WriteLine(sprintf "%A" list)
Run Code Online (Sandbox Code Playgroud)

使用printf或者sprintf它的好处是它还自动处理其他F#类型(例如,如果你有一个包含元组,有区别的联合或记录的列表).

  • 我注意到带有seq <'a>的"%A"不会只打印几个元素(然后是省略号).我使用Seq.toList将其转换为列表. (5认同)
  • %A不打印整个列表:`printf"%A"[1 .. 500] ;;`停在'100`. (3认同)
  • 看起来你是对的。总是有`list |&gt; List.map (sprintf "%A") |&gt; String.concat ", " |&gt; sprintf "[%s]"` 那么! (2认同)

Jar*_*Par 19

不,如果不使用循环/循环排序,则无法打印F#列表的内容.要打印每个元素,您必须枚举每个元素.

在F#虽然它不需要用循环来完成,但可以通过一个很好的管道操作来完成

[1;2;3;4;5] |> Seq.iter (fun x -> printf "%d " x)
Run Code Online (Sandbox Code Playgroud)

正如朱丽叶指出的那样,我可以通过部分应用进一步简化这一过程

[1;2;3;4;5] |> Seq.iter (printf "%d ")
Run Code Online (Sandbox Code Playgroud)

  • `[1; 2; 3; 4; 5] |> Seq.iter(printf"%d")` - w00t,currying :) (11认同)
  • `for [1; 2; 3; 4; 5]中的x执行printf"%d"x` - 我实际上认为简单的for循环与`Seq.iter`一样好.它当然取决于,但在某些情况下,我个人更喜欢直截了当(可能更为迫切?)的解决方案. (3认同)

ssp*_*ssp 7

通常,如果要更改printf"%A"打印对象作为fsi.exe显示类型值的方式,可以将StructuredFormatDisplayAttribute属性应用于您的类型:

[<StructuredFormatDisplayAttribute("PP {PrettyPrinter}")>]
type Foo(a:string array) =
  let pp = Array.mapi (fun i (s: string) -> sprintf "{idx: %d len: %d contents: '%s'}" i s.Length s) a
  member x.PrettyPrinter = pp

> let foo = Foo [|"one";"two";"three"|];;
val foo : Foo =
  PP [|"{idx: 0 len: 3 contents: 'one'}"; "{idx: 1 len: 3 contents: 'two'}";
       "{idx: 2 len: 5 contents: 'three'}"|]

> printfn "%A" foo;;
PP [|"{idx: 0 len: 3 contents: 'one'}"; "{idx: 1 len: 3 contents: 'two'}";
     "{idx: 2 len: 5 contents: 'three'}"|]
val it : unit = ()
Run Code Online (Sandbox Code Playgroud)