Skip to content

Instantly share code, notes, and snippets.

@wolever
Created December 25, 2009 04:48
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 wolever/263513 to your computer and use it in GitHub Desktop.
Save wolever/263513 to your computer and use it in GitHub Desktop.
-module(trie).
-export([new/0, add/2, step/2, from_dict/0, at_word/1]).
setdefault(Key, Default, Dict) ->
case dict:find(Key, Dict) of
{ ok, Value } ->
{ Dict, Value };
error ->
{ dict:store(Key, Default, Dict), Default }
end.
new() ->
dict:new().
add([], Trie) ->
dict:store(stop, true, Trie);
add([Ch|Rest], Trie) ->
{ NewTrie, SubTrie } = setdefault(Ch, dict:new(), Trie),
NewSubTrie = add(Rest, SubTrie),
dict:store(Ch, NewSubTrie, NewTrie).
step(Ch, Trie) ->
dict:find(Ch, Trie).
from_dict() ->
{ ok, File } = file:open("/usr/share/dict/words", [read]),
%{ ok, File } = file:open("/tmp/x", [read]),
from_dict(new(), File).
from_dict(CurTrie, File) ->
case io:get_line(File, "") of
eof ->
file:close(File),
CurTrie;
UnfixedLine ->
Line = string:strip(string:to_lower(UnfixedLine), both, $\n),
NewTrie = add(Line, CurTrie),
from_dict(NewTrie, File)
end.
at_word(Trie) ->
case dict:find(stop, Trie) of
{ ok, _ } -> true;
error -> false
end.
%
% Example usage
%
word_in_trie([], Trie) -> at_word(Trie);
word_in_trie([Ch|Rest], Trie) ->
case trie:step(Ch, Trie) of
{ ok, NextTrie } ->
word_in_trie(Rest, NextTrie);
error ->
false
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment