Can I insert into a map by key in F#? -


i'm messing around bit f# , i'm not quite sure if i'm doing correctly. in c# done idictionary or similar.

type school() =    member val roster = map.empty get, set     member this.add(grade: int, studentname: string) =       match this.roster.containskey(grade)         | true -> // can this.roster.[grade].insert([studentname])?         | false -> this.roster <- this.roster.add(grade, [studentname]) 

is there way insert map if contains specified key or using wrong collection in case?

the f# map type mapping keys values ordinary .net dictionary, except immutable.

if understand aim correctly, you're trying keep list of students each grade. type in case map integers lists of names, i.e. map<int, string list>.

the add operation on map either adds or replaces element, think that's operation want in false case. in true case, need current list, append new student , replace existing record. 1 way write like:

type school() =    member val roster = map.empty get, set     member this.add(grade: int, studentname: string) =      // try current list of students given 'grade'      let studentsopt = this.roster.tryfind(grade)       // if result 'none', use empty list default       let students = defaultarg studentsopt []      // create new list new student @ front      let newstudents = studentname::students      // create & save map new/replaced mapping 'grade'      this.roster <- this.roster.add(grade, newstudents) 

this not thread-safe (because calling add concurrently might not update map properly). however, can access school.roster @ time, iterate on (or share references it) safely, because immutable structure. however, if not care that, using standard dictionary fine - depends on actual use case.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -