A Postcard Catalogue That Knows Prefixes
A postcard postmarked Halifax belongs in my catalogue even when the date is too faint to read. I can record the place separately from my best guess at the year, then come back to the date when I have a magnifier and better light. But once the collection grows, finding every card from places beginning with Hal becomes its own little problem.
A trie gives each character a branch. Names with the same beginning share a path, so Halifax and Hamilton both start at H, then a, before going their separate ways. The structure dates to the early 1960s, when researchers were exploring ways to retrieve words by their spelling.
Here is a tiny JavaScript catalogue. It stores place names and asks whether a prefix has a path:
const root = new Map();
for (const name of ['Halifax', 'Hamilton', 'Calgary']) {
let node = root;
for (const ch of name.toLowerCase()) {
if (!node.has(ch)) node.set(ch, new Map());
node = node.get(ch);
}
}
function hasPrefix(prefix) {
let node = root;
for (const ch of prefix.toLowerCase()) {
node = node.get(ch);
if (!node) return false;
}
return true;
}
console.log(hasPrefix('Hal'), hasPrefix('Van')); // true false
Erlang builds the same shape with nested maps. Save this as postcards.erl, then compile and run it with erlc postcards.erl and erl -noshell -s postcards main -s init stop:
-module(postcards).
-export([main/0]).
insert([], Tree) -> Tree;
insert([C | Rest], Tree) ->
Tree#{C => insert(Rest, maps:get(C, Tree, #{}))}.
has_prefix([], _) -> true;
has_prefix([C | Rest], Tree) ->
case maps:find(C, Tree) of
{ok, Child} -> has_prefix(Rest, Child);
error -> false
end.
main() ->
Tree = lists:foldl(fun insert/2, #{}, ["halifax", "hamilton", "calgary"]),
io:format("~p ~p~n", [has_prefix("hal", Tree), has_prefix("van", Tree)]).
Both versions print true false. Following a prefix takes one step per character, regardless of how many names share it. The price is a collection of small maps, which can use more memory than a simple list for a modest album.
These examples answer only whether a prefix exists: they don’t distinguish a complete name from the beginning of a longer one. A working catalogue could add an end-of-name marker and attach card records there. I would still keep the actual postcards in suitable sleeves; a tidy index is no substitute for careful storage.