Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 410
Chris T Avatar asked Sep 27 '18 02:09

Chris T


People also ask

How do you return a function in OCaml?

OCaml doesn't have a return keyword — the last expression in a function becomes the result of the function automatically.


1 Answers

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.

like image 63
Jack Avatar answered Oct 31 '22 06:10

Jack