I'm trying to test some F# code from the Beginning F# book but am getting 'not defined' error with the reference to 'Seq.generate'. (I'm using VS2010 - so this may have worked with earlier vn of VS/F#)
FWIW I've also installed the F# Powerpack dll, but that does not seem to make a difference.
Is there a workaround/alternative her开发者_如何学Pythone?
/// execute a command using the Seq.generate
let execCommand (connName: string) (cmdString: string) =
Seq.generate
// This function gets called to open a connection and create a reader
(fun () -> openConnectionReader connName cmdString)
// This function gets called to read a single item in
// the enumerable for a reader/connection pair
(fun reader -> readOneRow(reader))
(fun reader -> reader.Dispose())
You can definitely use Seq.generate
from the F# PowerPack (either by referencing it, or more easily just by copying it from the source). I think that the function was removed because you can now handle disposal of objects using the use
keyword.
Writing this using the readOneRow
function would require using mutable state, but you can probably rewrite it by using something like this:
/// execute a command using the Seq.generate
let execCommand (connName: string) (cmdString: string) =
seq { use reader = openConnectionReader connName cmdString
while reader.ReadNext() do
// Read some information from the reader (as done in 'readOneRow')
let a = reader.GetInt32(0) // (e.g. ..or something like that)
yield a // generate next element of the sequence
}
The use
keyword properly disposes of the reader, so that's done automatically for you. The Seq.generate
function is quite nice, but I think that writing the same thing explicitly is probably more readable most of the time. (Especially if you're not using readOneRow
anywhere else).
generate can be found in FSharp.PowerPack.Compatibility:Compat.Seq.fs
精彩评论