Skip to content

Instantly share code, notes, and snippets.

@kunigami
Last active May 23, 2017 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kunigami/ce2ee00676d72ad66e0cf7832fa82f14 to your computer and use it in GitHub Desktop.
Save kunigami/ce2ee00676d72ad66e0cf7832fa82f14 to your computer and use it in GitHub Desktop.
(* Search for all subsequences of s in a trie *)
let rec searchSubsequenceImpl
(s: char list)
(trie: trie)
: char list list = match s with
| [] -> []
| first_char :: rest_s ->
let Node(children, _) = trie in
(* Branch 1: Pick character *)
let withChar = if Trie.ChildList.mem first_char children
then
let nextNode = Trie.ChildList.find first_char children in
let matches = searchSubsequenceImpl rest_s nextNode in
let Node(_, next_is_word) = nextNode in
let fullMatches = if next_is_word then ([] :: matches) else matches in
(* Add the current matching character to all matches *)
List.map (fun word -> first_char :: word) fullMatches
else []
in
(* Branch 2: Do not pick character *)
let withoutChar = searchSubsequenceImpl rest_s trie
in
(* Merge results *)
withChar @ withoutChar
let searchSubsequence (s: string) (trie: trie): string list =
let chars = BatString.to_list s in
let results = searchSubsequenceImpl chars trie in
List.map BatString.of_list results |> removeDuplicates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment