Skip to main content
Version: 1.6.0

Searching

The predicate Map.mem tests for membership in a given map, given a purported key.

const my_map: map<int,string> =
Map.literal([[1,"one"],[2,"two"]]);
const contains_2: bool = Map.mem(2, my_map); // == true

In practice, however, we would like to get the value associated to the key we searched. This is achieved by means of Map.find_opt.

const v : option<string> = Map.find_opt(2, my_map);

Notice how the value we read is an optional value: this is to force the reader to account for a missing key in the map. This requires pattern matching.

let force_access = (key, map) => {
return match(Map.find_opt (key, map)) {
when(Some(value)): value;
when(None): failwith("No value.")
};
};

In fact, the predefined function Map.find does exactly that, except that the exception raised by failwith carries the default string "MAP FIND".

Note: See the predefined namespace Map