Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# working with while loop

Tags:

f#

I have a datareader and i want to return collection of rows from it, after reading books for like a day i am not able to find out best way to do it in f#. I can do it normal C# way in F# but that is not why i am using f#

Here is what i am trying to achieve

let values =
    while reader.Read() do
        yield reader.GetString(0), reader.GetInt64(1)

Above is how i am trying to do

  • all values get collected into values, which could be dictinary or tuples or any collection
  • yield can't be used in while loop but that is what i am trying to do

What could be the best way to achieve this

like image 848
mamu Avatar asked Jun 05 '10 14:06

mamu


People also ask

What is Mtouch Facebook?

Facebook Touch is an advanced Facebook app that has many distinct features. H5 apps developed it as an app made especially for touchscreen phones. Available and applicable across all smartphones, Facebook Touch offers a fine user interface and serves as an alternative to the typical Facebook App.


2 Answers

F# also provides list comprehension for arrays and sequences.

let records_as_list = 
    [
        while reader.Read() 
            do yield (reader.GetString(0), reader.GetInt64(1)) 
    ]

let records_as_array = 
    [|
        while reader.Read() 
            do yield (reader.GetString(0), reader.GetInt64(1)) 
    |]

let records_as_sequence = 
    seq {
        while reader.Read() 
            do yield (reader.GetString(0), reader.GetInt64(1)) 
    }

F# has a convenient dictionary function built in called dict

let records_as_IDictionary = dict records_as_sequence
like image 106
gradbot Avatar answered Sep 20 '22 08:09

gradbot


You can use sequence expressions to implement enumerators:

let records = seq { while reader.NextResult() do yield (reader.GetString(0), reader.GetInt64(1)) }

If you need more than two fields, you can yield maps of column index (or name) -> field values (untested code):

let dbSchema = reader.GetSchemaTable()

let makeMap (rdr : IDataReader) (schema : DataTable) =
    schema.Columns |> Seq.cast<DataColumn> |> Seq.map (fun col -> (col.ColumnName, rdr.[col.ColumnName])) |> Map.ofSeq

let records = seq { while reader.NextResult() do yield (makeMap reader dbSchema) }
like image 39
Mau Avatar answered Sep 18 '22 08:09

Mau