Confused about HashTable default value documentation

In the docs for HashTables it states

If you remove a key, its previous value becomes again the default one associated to the key.

but a default value is never defined. The example shows that it returns the next value associated to the key in LIFO order. My question is, is there a default value assigned to a key somehow or is the return of HashTbl.find key presumed to be the head of a list of associated values for that key?

Your second guess is the correct one. Adding a binding (with Hashtbl.add) shadows the previous existing binding (if any). And if you remove the last remaining binding of a given key, the next call to Hashtbl.find will raise Not_found. There is no “default value” that would be returned if a key is not bound.

I’m assuming this behavior is there to implement environments (binding from variables to things in a programming languages) and allow shadowing without having to handle it by hand, but it is a bit unusual w.r.t to other languages.

1 Like

The common advice is to avoid Hashtbl.add and only ever use Hashtbl.replace.