I’m just starting to learn F#. I wrote this F#/ADO.NET code last night.
In what ways would you improve the syntax – make it feel like idiomatic F#?
let cn = new OleDbConnection(cnstr)
let sql = "SELECT * FROM People"
let da = new OleDbDataAdapter(new OleDbCommand(sql, cn))
let ds = new DataSet()
cn.Open()
let i = da.Fill(ds)
let rowCol = ds.Tables.[0].Rows
let rowCount = rowCol.Count
printfn "%A" rowCount
for i in 0 .. (rowCount - 1) do
let row:DataRow = rowCol.[i]
printfn "%A" row.["LastName"]
Note: I did find the syntax checker did not like
rowCol.[i].[“LastName”]
What is the proper way to handle dual-indexers? I had to break up the code over two lines.
Also If I hadn’t gone down the DataSet route and used a SqlDataReader that loaded its data into F# records. What collection structure should I use for containing the records?
The standard .NET List<>?
The key part of your code deals with .NET API that is not functional, so there is no way to make this part of the code particularly more idiomatic or nicer. However, the key thing in functional programming is abstraction, so you can hide this (ugly) code into some idiomatic and reusable function.
For representing collections of data in F#, you can either use standard F# list type (which is good for functional data processing) or
seq<'a>(which is standard .NETIEnumerable<'a>under the cover), which works nicely when working with other .NET libraries.Depending on how you access database elsewhere in your code, the following could work:
Now you can use the
queryfunction to write your original code roughly like this:Another example you could write is:
BTW: Regarding the suggestion by Mau I wouldn’t use higher-order functions excessively if there is a more direct way to write the code using language constructs such as
for. The example withiterabove is simple enough and some people will find it more readable, but there is no general rule…