简体   繁体   English

F#将列表输出到文件

[英]F# output a list to a file

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. 我是一名学习F#的学生,目前正在尝试将列表输出到通过聚类算法从分析创建的文件中。 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: 我想我已经接近了,但从第二个elem处收到了错误消息:“类型'int列表'与byte,int16,int32,int64,sbyte,uint16,uint32,uint64,nativeint, unativeint,源于使用printf样式的格式字符串”,这是我的代码:

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. 先感谢您。

What is clusteredIds ? 什么是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)? 我的猜测是这是一个列表列表(嵌套列表代表您要生成的CSV列)?

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). 如果clusteredIds只是一个数字列表,那么您的代码将起作用(然后您将获得将它们写入空格分隔的文件的代码)。 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循环和String.concat产生由逗号分隔(但在最后没有额外的逗号)号的一行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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