module use "std/mapopt.nib"
Map.Opt
Map.Opt.get — look up a key and answer an Option instead of raising when it is missing.
Map.get raises Err.MissingField for a key the Map does not hold, which is right when a missing key is a bug. When it is an ordinary outcome, Map.Opt.get asks the same question and answers an Option: Option.Some(v) when the key is there, Option.None when it is not.
Map.get_or also avoids the raise, but it cannot tell you whether the key was there: a stored value equal to the default looks the same as a missing key. Map.Opt.get keeps that difference, and Option.unwrap_or supplies the default afterwards when you want one. Add use "std/mapopt.nib" to reach it, and use "std/option.nib" as well to match on the answer or call the Option helpers.
let stock = {"apples": 0, "pears": 4};
let report = { k ->
match Map.Opt.get(stock, k)
Some(n) => "{k}: {n}"
None => "{k}: not stocked"
end };
(report("apples"), report("plums"), Map.get_or(stock, "apples", 0), Map.get_or(stock, "plums", 0))
("apples: 0", "plums: not stocked", 0, 0)
Functions
func get :: m: Map<'k, 'v>, k: 'k -> Option.Option<'v>
The value stored under k as Some(v), or None if k is not a key of m. Never raises.
let ages = {"ada": 36, "bo": 31};
(Map.Opt.get(ages, "ada"), Map.Opt.get(ages, "cy"), Option.unwrap_or(Map.Opt.get(ages, "cy"), 0))
(Option.Some(36), Option.None, 0)