Skip to content

Instantly share code, notes, and snippets.

@sillypog
Created May 30, 2018 05:09
Show Gist options
  • Save sillypog/03a026bb3b0ec0942d59ed2e843b1295 to your computer and use it in GitHub Desktop.
Save sillypog/03a026bb3b0ec0942d59ed2e843b1295 to your computer and use it in GitHub Desktop.
Building a trie of characters from a list of words
def build_tree(word_list) do
Enum.reduce(word_list, %{}, fn(word, tree) ->
word
|> String.codepoints
|> place_chars(tree)
end)
end
def place_chars([], current_node), do: current_node
def place_chars([h | t], current_node) do
case current_node[h] do
nil ->
Map.put(current_node, h, place_chars(t, create_next_node(t)))
next_node ->
Map.put(current_node, h, place_chars(t, next_node))
end
end
def create_next_node([]), do: :leaf
def create_next_node(_), do: %{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment