wang kai
wang kai

Reputation: 1747

How to set the result of File.ReadAllLines to ResizeArray or Array in f#?

I have this prog:

let mutable lines=new ResizeArray<string>()

let paramLines=
 if File.Exists(maincfPath) then
   lines=File.ReadAllLines(maincfPath)
 else
   Environment.Exit(0)

the type of File.ReadAllLines is string[],If I use Array.zeroCreate,I have to decide a initial num,but I have not use File.ReadAllLines,so I don't know the num.If I use ResizeArray,It's type is ResizeArray,I can't pass string[] to it.

How to slove this problem?Thanks!

Upvotes: 2

Views: 77

Answers (3)

Gerard
Gerard

Reputation: 483

If possible please avoid reading ALL Lines into memory with ReadAllLines, it is not good for your memory and it is good practice to avoid. Try using File.ReadLines instead as it will return a seq<string>, reading the lines one-by-one into memory, not all at once.

for line in File.ReadLines(path) do
    … // do something with line

if you do not want to enumerate the line there, it still is just a seq<string> (which is an alias of IEnumerable<string>), so you can pass it to functions and code that can handle seq, like Seq Module, and you are getting good responsible memory management consuming only one row at a time, rather then loading the whole file into memory and an enormous string that will likely end up on the LOH.

To answer your question, although you should not do this

  if File.Exists(maincfPath) then
    let lines = File.ReadAllLines(maincfPath) // readAllLines creates line array not you
    … // use lines here (or call function that uses lines)
  else
    Environment.Exit(0)

As was aready given … but once again, avoid loading all lines into memory if possible.

Upvotes: 0

AMieres
AMieres

Reputation: 5004

No need to declare or initialize a mutable array. Just use let to bind a name to the result of ReadAllLines

if File.Exists(maincfPath) then
   let lines = File.ReadAllLines(maincfPath)
   ... // do something with lines
else
   Environment.Exit(0)

when handling errors, I prefer using if then else this way, which avoids the arrow pattern:

 if File.Exists(maincfPath) |> not then Environment.Exit(0) else
 let lines = File.ReadAllLines(maincfPath)
 ... // do something with lines

Upvotes: 4

TeaDrivenDev
TeaDrivenDev

Reputation: 6629

You can just use the empty array [||], as that will be replaced anyway with the array that File.ReadAllLines() creates.

Upvotes: 2

Related Questions