I am a student trying to learn F# for my class. I have been progressing steadily by myself, but I have run into a problem that I just can't wrap my head around. I was given an assignment to read and add data to a CSV database file. I have figured out how to sort the data into columns and rows using F Sharp.Data, but I've had a lot of difficulty figuring out how to count items and search through the list to find the data I need. I am a visual learner, so if I could just look at some examples that are sorting through similar lists for strings and floats I could probably figure it out myself.
This is the code that I have so far (I apologize for the sloppiness I'm not the best at posting code on this site yet)
open System.IO
open System.Net
open F Sharp.Data
open System
[<Literal>]
let Template = __SOURCE_DIRECTORY__ + @"\students.txt" // Creating the directory
type Students = CsvProvider< Template > // I can format the list using FSharp.Data here
let students = Students.Load(Template)
let FirstRow = students.Rows |> Seq.head //Creating the header
let TMP = 0
let UTG = 0 //counter vars for later use
for rows in students.Rows do // Reading list correctly now have to figure out how to count elements
printfn "%A" rows.Last
//printfn "%A" TMP
//let tmp = Students.Parse //Graveyard of Trial and ERRO
//let tst = 0
//for Rows in students do
// tst = tst + 1
As you can see from my code, I have sorted the list into columns and rows. If someone could show me how to do counters and to search for specific Items in the list It would be much appreciated.
I know a lot of people just dump assignments on this site and expect people to do them, and that's terrible. you're not learning if you don't do the assignment yourself. I just need some help understanding it better.
Best regards- A CS major who needs a cup of coffee, Joe
The easiest way to do various counting, searching and filtering tasks over a collection of data (such as rows of a CSV file in your example) is to use the built-in higher-order functions for collection processing.
There is a very good overview in an article Choosing between collection functions by Scott Wlaschin, which also has numerous practical examples that can help you.
In your example, you are already using Seq.head
which gives you the first item from a sequence:
students.Rows |> Seq.head
This is a very good start. You can do many other things using other functions that are available in the Seq
module. If you type Seq
and then .
most editors will show you an auto-complete list with all the available functions (and the above article documents what they do).
For example, if you want to do counting, Seq.length
might be useful. For various filtering tasks, try Seq.filter
and, finally, for searching there is Seq.find
.