It works with a for loop and mutable variable:
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
But it is very "non-functional" so I'm curious what is the proper way to do this? I figured how to append the index number to a list of strings:
let rec addIndex (startInd:int) l=
match l with
|x::xs -> startInd.ToString()+x :: (addIndex (startInd+1) xs)
|[] -> []
But it won't apply to 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
Is reading the whole file into memory as a list the only way to do this? Is there something like seq.count so it can be done similar to the following?
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