【发布时间】:2015-12-19 03:50:26
【问题描述】:
它适用于 for 循环和可变变量:
let addLnNum filename =
use outFile = new StreamWriter(@"out.txt")
let mutable count = 1
for line in File.ReadLines(filename) do
let newLine = addPre (count.ToString()) line
outFile.WriteLine newLine
count <- count + 1
但它非常“不起作用”,所以我很好奇这样做的正确方法是什么? 我想出了如何将索引号附加到字符串列表:
let rec addIndex (startInd:int) l=
match l with
|x::xs -> startInd.ToString()+x :: (addIndex (startInd+1) xs)
|[] -> []
但它不适用于 File.ReadLines:
let addLnNum2 filename =
use outFile = new StreamWriter(@"out.txt")
File.ReadLines(filename)
|> addIndex 1
|> ignore
//Error 1 Type mismatch. Expecting a Collections.Generic.IEnumerable<string> -> 'a
//but given a string list -> string list
将整个文件作为列表读入内存是唯一的方法吗?有没有类似 seq.count 的东西,所以可以像下面这样完成?
let addLnNum3 filename =
use outFile = new StreamWriter(@"out.txt")
File.ReadLines(filename)
|> Seq.map (fun s -> Seq.count + s) //no such thing as Seq.count
|> Seq.iter outFile.WriteLine
|> ignore
【问题讨论】: