Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to a Map in F# using a for loop

Code:

let studentMap =
    for i = 0 to count do
        Map.empty.Add(students.[i].getId(), students.[i].getScores())

I am trying to add to a map sequentially. I have student objects in an array and am trying to add them in order. I am confused at how to do this. I thought maybe you make an empty map then add to it in order via a for loop, but it always causes trouble and won't work. Is there a way to add items to a map using a for loop? The <key/value> pairs are this: <string, int array>. That is the way I want it formatted but it keeps giving me trouble. I'll restate the goal again to clarify: I want to be able to add items to a map using a for loop with my student objects array being used to get the appropriate data I need in there. I will be able to give it a string and get back that student's grades for example. I know it's a weird problem I'm working on, but I needed to try something simple at first.

like image 576
Sacred Avatar asked Dec 04 '22 06:12

Sacred


1 Answers

You can try a more functional idiomatic approach:

Let's say you have an array of type Student (in the example below is an empty array):

let students = Array.empty<Student>

You can transform your array in to a Map:

let mapStudents = students 
                    |> Array.map (fun s -> (s.getId(), s.getScore()))
                    |> Map.ofArray
like image 67
polkduran Avatar answered Jan 08 '23 10:01

polkduran