Question

I have defined some types as follows:

module SMap = Map.Make(String)

type s = 
  { t: int
    fa: int list } 

type t = s SMap.t

I would like to write a function modify to add 100 to the list fa for the element corresponding to key. The following code works:

let modify (key: String) (x: t) =
  let a = SMap.find key x in
  SMap.add key { a with fa = a.fa @ [100] } (SMap.remove key x)

However, removing and adding an element looks redundant for me... Could any tell me if there is a better way to directly modify it?

Was it helpful?

Solution

Yes, you can just add it.

A map can contain a key only once, so if you add another mapping with this key, it will remove the previous one.

http://caml.inria.fr/pub/docs/manual-ocaml/libref/Map.Make.html#VALadd

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top