2
votes

I am a student learning F# and at the moment am attempting to output a list to a file created from analysis through a clustering algorithm. I think I am close but I am getting the error message from the second elem: "The type 'int list' is not compatible with any of the types byte,int16,int32,int64,sbyte,uint16,uint32,uint64,nativeint,unativeint, arising from the use of a printf-style format string" Here is my code:

let printNumbersToFile fileName =
   use file = System.IO.File.CreateText(fileName)
   clusteredIds
   |> List.iter (fun elem -> fprintf file "%d " elem)
   fprintfn file ""
printNumbersToFile "C:\Users\Jessica\Desktop\CTU Stuff\Dissertation\Programs For Dissertation\Fsharp\DensityClustering\Test.csv"

Any help would be greatly appreciated. Thank you in advance.

1
I remade it as but now it is just producing and empty file how did I miss the I/O? : let file = new StreamWriter("C:\Users\Jessica\Desktop\CTU Stuff\Dissertation\Programs For Dissertation\Fsharp\DensityClustering\Test.csv") clusteredIds |> List.iter (fun nested -> nested |> List.iter (fun elem -> fprintf file "%d " elem) fprintf file "\n") - RedMassiveStar
Try calling file.Close() at the end - or better, if this is in a function, you can write use file = .... See: msdn.microsoft.com/en-us/library/dd233240.aspx - Tomas Petricek
One other point--off topic I guess but if I were you I'd write the file name as "C:/Users/Jessica/Desktop . . . " It works equally well and then you don't have to worry about escaping anything in the string. - Onorio Catenacci

1 Answers

5
votes

What is clusteredIds? My guess is that it is a list of lists (where the nested lists represent columns of the CSV that you want to produce)?

Your code would work if clusteredIds was just a list of numbers (and then you'd have code that writes them to a file separated by spaces). If you want to write nested list, then you need to have two nested iterations. Perhaps something like:

clusteredIds
|> List.iter (fun nested -> 
    nested |> List.iter (fun elem -> fprintf file "%d " elem)
    fprintf file "\n")

Or it might be easier to use for loop and String.concat to generate a single line with numbers separated by comma (but with no additional comma at the end):

for nested in clusteredIds do
  fprintf file "%s" (String.concat "," (Seq.map string nested))