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

前端 未结 4 1385
梦谈多话
梦谈多话 2021-01-31 15:20

Is it possible to print full list without using cycle? I tried:

Console.WriteLine([1;2;3;4;5])

and it prints only three first elements:

相关标签:
4条回答
  • 2021-01-31 15:59

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

    0 讨论(0)
  • 2021-01-31 16:03

    A perhaps more functional way of doing it:

    let nums = [1;2;3;4;5;6]
    let concat acc x = acc + " " + (string x)
    let full_list = List.fold concat "" nums
    printfn "%s" full_list
    
    0 讨论(0)
  • 2021-01-31 16:04

    No it's not possible to print the contents of an F# list without using a cycle / loop of sorts. To print every element you must enumerate each of them.

    In F# though it doesn't need to be done with a loop though but instead can be done with a nice pipe operation

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

    And as Juliet pointed out I could simplify this further with partial application

    [1;2;3;4;5] |> Seq.iter (printf "%d ")
    
    0 讨论(0)
  • 2021-01-31 16:07

    In general, if you want to change as a way an printf "%A" prints your objects as a way fsi.exe shows values fo your type, you can apply StructuredFormatDisplayAttribute attribute to your type:

    [<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 = ()
    
    0 讨论(0)
提交回复
热议问题