简体   繁体   中英

F# - Write List Of Tuples To CSV File

I need to write a list of tuples to a csv file. The tuples could have a variable number of fields and types! My current effort is as follows:

module SOQN = 

    open System
    open System.IO
    open FSharp.Data

    let lstTuples = [(2, false, 83.23, "Alpha", 29); (3, true, 79.11, "Beta", 47); (5, false, 61.13, "Gamma", 71)]

    let main() =
        do 
            use writer = new StreamWriter(@"C:\tmp\ListTuples.csv")
            let lstTuplesIter = lstTuples |> List.iter writer.WriteLine
            lstTuplesIter
        0

    [<EntryPoint>]
    main() |> ignore

// Actual Output: 
// (2, False, 83.23, Alpha, 29)
// (3, True, 79.11, Beta, 47)
// (5, False, 61.13, Gamma, 71)
// 
// Expected Output: 
// 2, False, 83.23, Alpha, 29
// 3, True, 79.11, Beta, 47
// 5, False, 61.13, Gamma, 71
//

What am I missing?

Although I agree with @Jackson that this is probably not the right data structure, for arbitrary length you will probably need reflection.

You see how they access components of a tuple ("ItemN" where N is a number) here .

You could iterate over the properties and get the values for your dynamic case.

Keep in mind that using reflection is pretty inefficient (see here )

您正在做的是写出元组的F#文本解释,其中包括括号,如果您对元组进行解构并使用sprintf格式化输出,则可以得到所需的结果:

lstTuples |> List.iter (fun (a,b,c,d,e) -> writer.WriteLine (sprintf "%d,%A,%.2f,%s,%d" a b c d e ))

Thanks to you both for the benefit of your expertise. The following snippet works, as required (adapting Tomas Petricek's code):

module SOANS = 

open System
open System.IO
open FSharp.Reflection
open FSharp.Data

let lstTuples = [(2, false, 83.23, "Alpha", 29); (3, true, 79.11, "Beta", 47); (5, false, 61.13, "Gamma", 71)]

// https://stackoverflow.com/questions/13071986/write-a-sequence-of-tuples-to-a-csv-file-f    
let tupleToString t = 
  if FSharpType.IsTuple(t.GetType()) then
    FSharpValue.GetTupleFields(t)
    |> Array.map string
    |> String.concat ", "
  else failwith "not a tuple!"

let allIsStrings t = 
  t 
  |> Seq.map tupleToString
  |> Array.ofSeq

let main() =
    let lstTuples = [(2, false, 83.23, "Alpha", 29); (3, true, 79.11, "Beta", 47); (5, false, 61.13, "Gamma", 71)]
    let outTest = allIsStrings(lstTuples)
    File.WriteAllLines(@"C:\tmp\ListTuples.csv", outTest)
    0

[<EntryPoint>]
main() |> ignore

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM