F# working with DataReader

烂漫一生 提交于 2021-02-07 19:15:03

问题


let reader = selectCommand.ExecuteReader()

let getBytesData (x : IDataReader) = 
    let len = reader.GetBytes(1, int64 0, null, 0, 0);
    // Create a buffer to hold the bytes, and then
    // read the bytes from the DataTableReader.
    let buffer : byte array = Array.zeroCreate (int32 len)
    x.GetBytes(1, int64 0, buffer, 0, int32 len) |> ignore
    buffer

let retVal = 
  List [ while reader.Read() do 
           yield (reader.GetString(0), getBytesData reader, 
                  reader.GetDateTime(2)) ]

I have above code to read bytes[] from datareader.

getBytesData function takes reader and returns bytes[] from reader.

  • everything works fine but it getBytesData function is working very non-functional way.
  • i am creates zero filled byte array just to create array, is there any way of creating dynamic expanding or fixed lenght array

Is there any way i can optimize in F#?

Sorry for kind of question, but i have started a new project on F# to squeeze all juice out of it, so trying to get each line most optimal way


回答1:


The GetBytes method of the IDataReader doesn't really provide any options for writing the code in a more functional way (it takes an array that it wants to modify, so we simply must give it some array...).

So your version of code is perfectly fine - even though it's not fully functional, you can at least keep the imperative part localized in that single function and keep the rest of your program functional (which is a good result)!

The only change I would do in your code is that I would move reader to the sequence comprehension (to make it more localized) and I would use the use keyword to make sure that it gets properly disposed (also, you don't need the List identifier in the sequence expression):

let retVal =  
  [ use reader = selectCommand.ExecuteReader() 
    while reader.Read() do  
      yield (reader.GetString(0), getBytesData reader,  reader.GetDateTime(2)) ]



回答2:


In my experience that is the best way to do this. Interacting with native .Net methods need to be used somewhat emparitiviley (thus the |> ignore), so encapsulating in a function then using the fn as part of your functional programming. I have asked questions related to using .Net methods in F# if you are interested.

Also make sure you dispose of the reader afterwards too.



来源:https://stackoverflow.com/questions/2983087/f-working-with-datareader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!