Created
March 27, 2009 16:39
-
-
Save bakkdoor/86772 to your computer and use it in GitHub Desktop.
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
-module(wordsort_sequential). | |
-export([start/1, start_file/1]). | |
-import(dict, [store/3, find/2]). | |
-author({"Christopher Bertels", "[email protected]"}). | |
start(String) -> | |
process(words(String)). | |
start_file(Filename) -> | |
{ok, File} = file:open(Filename, [read]), | |
process(words_from_lines(read_lines(File))). | |
process(Words) -> | |
WordDict = count_words(Words, dict:new()), | |
SortedWords = sorted_words(WordDict), | |
io:format("counted ~p words in total. Sorted word list following...~n", [length(Words)]), | |
WordDict, | |
lists:foreach(fun (Word) -> | |
{ok, WordCount} = find(Word, WordDict), | |
io:format("~p : ~p~n", [WordCount, Word]) | |
end, | |
SortedWords). | |
read_lines(Fd) -> | |
read_lines(Fd, []). | |
read_lines(Fd, LineBuffer) -> | |
case io:get_line(Fd, "") of | |
eof -> | |
LineBuffer; | |
Line -> | |
case Line -- "\n" of | |
"" -> | |
read_lines(Fd, LineBuffer); | |
GoodLine -> | |
read_lines(Fd, [GoodLine | LineBuffer]) | |
end | |
end. | |
%% returns all words of a string as a list. | |
words(String) -> | |
string:tokens(String, " "). | |
words_from_lines(Lines) -> | |
lists:foldl(fun lists:append/2, | |
[], | |
lists:map(fun(Line) -> | |
words(Line) | |
end, | |
Lines)). | |
%% increments the word's counter by 1 in Dict | |
count_word(Word, Dict) -> | |
case find(Word, Dict) of | |
{ok, Val} -> | |
store(Word, Val + 1, Dict); | |
_ -> | |
store(Word, 1, Dict) | |
end. | |
%% count all words in list and store results in Dict. | |
count_words([], Dict) -> | |
Dict; | |
count_words([Word|Rest], Dict) -> | |
count_words(Rest, count_word(Word, Dict)). | |
%% sort dictionary by values | |
sorted_words(Dict) -> | |
lists:sort(fun(X, Y) -> dict:find(X, Dict) >= dict:find(Y, Dict) end, | |
dict:fetch_keys(Dict)). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment