Trie Autocomplete
Tutorial Video
Text description (accessibility)
This video demonstrates the "Trie Autocomplete" functional Rust example. Difficulty level: Intermediate. Key concepts covered: Functional Programming. Autocomplete and prefix search are fundamental to user interfaces: search bars, IDE completion, spell checkers, and IP routing tables all need to answer "what words start with this prefix?" efficiently. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Autocomplete and prefix search are fundamental to user interfaces: search bars, IDE completion, spell checkers, and IP routing tables all need to answer "what words start with this prefix?" efficiently. A hash map of all words answers exact lookups in O(1) but cannot answer prefix queries. A trie (prefix tree) organizes strings by shared prefixes, enabling prefix queries in O(m) time where m is the prefix length — independent of how many words are stored. This also makes insertion, deletion, and "does any word start with X?" all O(m). Tries power the autocomplete in Google Search, the routing table lookup in routers, and the dictionary in word games.
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Node storage | HashMap<char, TrieNode> | Hashtbl or Map.Make(Char).t |
| Insertion | Mutable traversal with entry() | Mutable Hashtbl or immutable path copy |
| Completions DFS | Recursive with &mut Vec<String> | Accumulator list or Buffer |
| Memory | Each node heap-allocated | GC-managed, similar cost |
| Sorted output | Extra sort step | Map gives sorted iteration free |
| End marker | bool field | bool field or unit option |
OCaml Approach
OCaml represents trie nodes as { children: (char * node) list; is_end: bool } or with a Hashtbl. Functional insertion creates a new node path, relying on structural sharing for efficiency. With mutable Hashtbl, insertion mutates like Rust's approach. OCaml's Map.Make(Char) creates a balanced BST per node for sorted child iteration — convenient for alphabetical autocomplete results. The DFS for completions uses continuation-passing or an accumulator list. OCaml's algebraic types make is_end a natural bool field.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Trie Autocomplete
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
delete(word) that removes a word while preserving words that share its prefix.Vec<String> + binary search for a dictionary of 100k words.