我来自c#和python背景,我觉得一定有更好的方法来读取文件和填充经典的F#列表。但是,我知道f#列表是不可变的。必须有使用List<string>对象并调用其Add方法的替代方法。
到目前为止,我手头的情况是:
let ptr = new StreamReader("stop-words.txt")
let lst = new List<string>()
let ProcessLine line =
match line with
| null -> false
| s ->
lst.Add(s)
true
while ProcessLine (ptr.ReadLine()) do () 如果我用python编写类似的东西,我会这样做:
[x[:-1] for x in open('stop-words.txt')]发布于 2013-11-29 12:58:04
简单解
System.IO.File.ReadAllLines(filename) |> List.ofArray尽管您可以编写递归函数
let processline fname =
let file = new System.IO.StreamReader("stop-words.txt")
let rec dowork() =
match file.ReadLine() with
|null -> []
|t -> t::(dowork())
dowork()发布于 2013-11-29 12:56:50
如果希望读取文件中的所有行,只需使用ReadAllLines即可。该方法将数据作为数组返回,但您可以使用List.ofArray轻松地将其转换为List.ofArray列表,也可以使用Seq模块中的函数处理它:
open System.IO
File.ReadAllLines("stop-words.txt")或者,如果不希望将所有内容读入内存,则可以使用File.ReadLines来延迟读取行。
https://stackoverflow.com/questions/20285858
复制相似问题