如何快速生成列表迭代文件(how to generate a list quickly iterating a file)
我来自ac#和python背景,觉得必须有更好的方法来读取文件并填充经典的F#列表。 但后来我知道af #list是不可变的。 必须有一个使用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')]Me coming from a c# and python background, feels there must be a better way to read a file and populate a classic F# list. But then I know that a f# list is immutable. There must be an alternative using a List<string> object and calling its Add method.
So far what I have at hand:
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 ()If I were to write the similar stuff in python I'd do something like:
[x[:-1] for x in open('stop-words.txt')]最满意答案
简单解决方案
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()Simple solution
System.IO.File.ReadAllLines(filename) |> List.ofArrayAlthough you can write a recursive function
let processline fname = let file = new System.IO.StreamReader("stop-words.txt") let rec dowork() = match file.ReadLine() with |null -> [] |t -> t::(dowork()) dowork()更多推荐
发布评论