Created
May 30, 2018 05:09
-
-
Save sillypog/03a026bb3b0ec0942d59ed2e843b1295 to your computer and use it in GitHub Desktop.
Building a trie of characters from a list of words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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