% ---------------------------------------------------------------------------- %
% wordfreq.m
% Ralph Becket <rbeck@microsoft.com>
% Tue Jan  9 15:56:12 GMT 2001
% vim: ts=4 sw=4 et tw=0 wm=0 ff=unix
%
% ---------------------------------------------------------------------------- %

:- module mytest.

:- interface.

:- import_module io.



:- pred main(io__state, io__state).
:- mode main(di, uo) is det.



:- implementation.



:- import_module string, int, list, require, std_util, char, map.



main -->
    count_word_freqs(map__init, FreqMap),
    { X = list__sort(list__map(func(K-V) = V-K, map__to_assoc_list(FreqMap))) },
    { Y = list__reverse(X) },
    io__write_list(Y, "\n", write_freq_word),
    io__nl.



:- pred count_word_freqs(map(string,int),map(string,int),io__state,io__state).
:- mode count_word_freqs(in, out, di, uo) is det.

count_word_freqs(FreqMap0, FreqMap) -->
    io__read_line_as_string(Result),
    (
        { Result = ok(Line) },
        { Words  = string__words(isnt(char__is_alpha),string__to_lower(Line)) },
        { Update =
            ( func(S, FM) = 
                ( if map__search(FM, S, N)
                  then FM ^ elem(S) := N + 1
                  else FM ^ elem(S) := 1
                )
            )
        },
        { FreqMap1 = list__foldl(Update, Words, FreqMap0) },
        count_word_freqs(FreqMap1, FreqMap)
    ;
        { Result = eof },
        { FreqMap = FreqMap0 }
    ;
        { Result = error(ErrNo) },
        { error(io__error_message(ErrNo)) }
    ).



:- pred write_freq_word(pair(int, string), io__state, io__state).
:- mode write_freq_word(in, di, uo) is det.

write_freq_word(Freq - Word) -->
    io__format("%7d\t%s", [i(Freq), s(Word)]).