Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize F# list when size is unknown, using while..do loop

I have a function that will parse the results of a DataReader, and I don't know how many items are returned, so I want to use a while..do loop to iterate over the reader, and the outcome should be a list of a certain type.

(fun(reader) ->
            [
                while reader.Read() do
                    new CityType(Id=(reader.GetInt32 0), Name=(reader.GetString 1), StateName=(reader.GetString 2))
            ])

This is what I tried, but the warning I get is:

This expression should have type 'unit', but has type 'CityType'. Use 'ignore' to discard the result of the expression, or 'let' 
to bind the result to a name.

So what is the best way to iterate over a DataReader and create a list?

like image 847
James Black Avatar asked Jan 19 '26 15:01

James Black


1 Answers

you can use list comprehension:

[
   while reader.Read() do
       let d =  new CityType(Id=(reader.GetInt32 0), Name=(reader.GetString 1), StateName=(reader.GetString 2))
       yield d
]

Here is one more example:

/// The squares of the first 10 integers
let squaresOfOneToTen = [ for x in 0..10 -> x*x ]

or

let squaresOfOneToTen = [ for x in 0..10 do yield x*x ]

You can also do it for sequences and arrays:

seq { 
   for i=1 to 9 do 
      for j=1 to 9 do
         yield (i,j,i*j)
}


[| for i=1 to 100 do yield i*i |]

you can also yield a sub sequence in a sequence(yield!), here is an example using Project Euler 31.

like image 63
Yin Zhu Avatar answered Jan 22 '26 09:01

Yin Zhu