F# reading and separating text from a file

611 views Asked by At

I have a txt file with numbers and comma separated lines like this for example.

4324,1dd3,444

4324,1fd3,444

4324,1as3,442

I have a function that takes a string as a parameter, and I want to check for each line if that string is equal to the second "word" of the line, so in line one that would be "1dd3". If that parameter matches the word I want to add the third word of the row to a string list (or save it some other way to use it later on in the code).

In C# I would simply loop through the list and use a split on the commas like this

while(reader.Peek > 0) //while txt file still has lines left to read
{
    split the row...
    compare it to argument
    add to list of strings
}

But I am fairly new to F# and can't find the right syntax and or method of doing this here, any help would be appreciated.

1

There are 1 answers

0
kaefer On BEST ANSWER

You could start by trying to determine 1) the appropriate data structure on which to operate, and 2) if there's a predefined library function already doing that what is needed. In this case I wouldn't waste time with reading the file line by line, reading it all at once instead. So it's an array to operate on.

The function needs to apply a chooser on all elements of the array, like a combination of filter and projection. So it's Array.pick/Array.tryPick if you're only interested in the first occurence, or Array.choose to retrieve all instances your predicate is true. Now all we do is pattern matching with a guard clause to check for your condition.

let findTextInFile nameOfFile txtToSearch =
    System.IO.File.ReadAllLines nameOfFile
    |> Array.choose (fun s ->
        match s.Split ',' with
        | [| _; y; z |] when y = txtToSearch -> Some z
        | _ -> None )

findTextInFile @"c:\temp\xxx" "1dd3"
// val it : string [] = [|"444"|]