Can I insert into a map by key in F#?
dictionary, f#
Solution
The F# `Map` type is a mapping from keys to values just like ordinary .NET `Dictionary`, except that it is immutable.
If I understand your aim correctly, you're trying to keep a list of students for each grade. The type in that case is a map from integers to lists of names, i.e. `Map<int, string list>`.
The `Add` operation on the map actually either adds or replaces an element, so I think that's the operation you want in the `false` case. In the `true` case, you need to get the current list, append the new student and then replace the existing record. One way to do this is to write something like:
type School() =
member val Roster = Map.empty with get, set
member this.Add(grade: int, studentName: string) =
// Try to get the current list of students for a given 'grade'
let studentsOpt = this.Roster.TryFind(grade)
// If the result was 'None', then use empty list as the default
let students = defaultArg studentsOpt []
// Create a new list with the new student at the front
let newStudents = studentName::students
// Create & save map with new/replaced mapping for 'grade'
this.Roster <- this.Roster.Add(grade, newStudents)
This is not thread-safe (because calling `Add` concurrently might not update the map properly). However, you can access `school.Roster` at any time, iterate over it (or share references to it) safely, because it is an immutable structure. However, if you do not care about that, then using standard `Dictionary` would be perfectly fine too - depends on your actual use case.
Problem
I'm messing around a bit with F# and I'm not quite sure if I'm doing this correctly. In C# this could be done with an IDictionary or something similar. ``` type School() = member val Roster = Map.empty with get, set member this.add(grade: int, studentName: string) = match this.Roster.ContainsKey(grade) with | true -> // Can I do something like this.Roster.[grade].Insert([studentName])? | false -> this.Roster <- this.Roster.Add(grade, [studentName]) ``` Is there a way to insert into the map if it contains a specified key or am I just using the wrong collection in this case?