SR3142
SR3142

Reputation: 610

F# sequences returning one item at a time

I am new to F# and I am trying to convert a DbDataReader class from c# to F#, the DBDataReader reads and returns a csv line as a list

member this.ReadCSV = 
    seq { 
        use textReader = File.OpenText(filename)
        while (not textReader.EndOfStream) do
            let line = textReader.ReadLine()
            // linedata is a class variable that holds the current data for use by DBDataReader
            linedata <- line |> Seq.toList |> splitDelimited delimiter "" [])
            yield true
        yield false
    }

the DBDataReader class has a Read() function that when called should move the cursor to the next line in the input, i implemented this using an index variable as below but this seems inefficient when processing a file with millions of rows. is there a more efficient way of doing this?

override this.Read() =
    let hasRows = Seq.item idx this.ReadCSV
    idx <- idx + 1
    hasRows

Upvotes: 0

Views: 190

Answers (1)

Why not use an Enumerator instead of a Sequence?

If you really want to use a Sequence in FP style, then

  1. yield option values from the sequence and
  2. replace the loop statement that uses this.Read() method with a for..in expression that uses this.ReadCSV as the enumerable-expression and
member this.CSV = 
    seq { 
        use textReader = File.OpenText(filename)
        while (not textReader.EndOfStream) do
            let line = textReader.ReadLine()
            yield (line |> Seq.toList |> splitDelimited delimiter "" [])
    }


for linedata in this.CSV do
    ...

Upvotes: 2

Related Questions