%%% -*- mode: erlang -*- %%% $Id: wc.erlang,v 1.5 2001/06/26 05:09:25 doug Exp $ %%% http://www.bagley.org/~doug/shootout/ -module(wc). -export([main/0, main/1]). % TBD - this program should not assume lines are less than 10000 characters long main() -> main(['1']). main(Args) -> Port = open_port({fd, 0, 1}, [eof, {line, 10000}]), wc(Port, 0, 0, 0), halt(0). wc(Port, NL, NW, NC) -> receive {Port, {_, {_, Line}}} -> wc(Port, NL + 1, NW + cw(Line, out, 0), NC + length(Line) + 1); {Port, eof} -> io:format("~w ~w ~w~n", [NL, NW, NC]) end. % count words in a line (list) cw([], _, Count) -> Count; cw([$\ |T], _, Count) -> cw(T, out, Count); cw([$\t|T], _, Count) -> cw(T, out, Count); cw([_|T], out, Count) -> cw(T, in, 1 + Count); cw([_|T], in, Count) -> cw(T, in, Count).