Chris T
Chris T

Reputation: 483

Using Map.update in OCaml

I am attempting to change the value of a key in a map I made in OCaml:

module TestMap = Map.Make(String);;
let m = TestMap.empty;;
let m = TestMap.add "Chris" 1 m ;;
let m = TestMap.add "Julie" 4 m;;

This compiles file, but when I try to update the value at key Julie with:

let m = TestMap.update "Julie" 10 m;;

I get an error from the compiler:

Error: This expression has type int but an expression was expected of type
         'a option -> 'a option

I'm guessing that I'm maybe using the function incorrectly. I'm finding the documentation for Map.update pretty hard to understand:

val update : key -> ('a option -> 'a option) -> 'a t -> 'a t

Is my syntax or are my arguments incorrect?

Upvotes: 5

Views: 3642

Answers (1)

Jack
Jack

Reputation: 133609

The update function works in a way different from what you think

key -> ('a option -> 'a option) -> 'a t -> 'a t

You see that second argument is a function which takes an 'a option and returns an 'a option so you don't directly update with a new value but rather pass a function which returns the new value, according to the previous one, eg:

let m = TestMap.update "Julie" (fun _ -> Some 10) m;;

This because, as documentation states, the passed 'a option tells you if there was a mapping for the key and the returned 'a option allows you to change it or even remove it (through None).

If you need just to update a mapping you can use Map.add again, there's no need to use more advanced Map.update.

Upvotes: 9

Related Questions