分散Grepっぽい何か

30分プログラム、その563。分散Grepっぽい何かを作ってみよう。
MapReduceといえばwcだけどgrepもおもしろいんじゃないかな、と思ったので作ってみた。
正直なところシングルCPUなボクのマシンでは、速くなっているのかどうかよく分からない。なんとなくIO処理に時間をとられて、分散にしてもあまり嬉しくないんじゃないか、という気がしてる。

使い方

$ escript grep.erl url *(.)
auth.py~:import urllib2
auth.py:import urllib2
auth.py:response = urllib2.urlopen('https://www.google.com/accounts/ClientLogin',
croquis_list.pl:            my $url = "http://d.hatena.ne.jp/mzp/$_->[0]/$1";
croquis_list.pl:            my $entry = "http://b.hatena.ne.jp/entry/$url";
croquis_list.pl:            my $img = "http://b.hatena.ne.jp/entry/image/$url";
croquis_list.pl:            print "- [$url:title] $bookmark\n"

ソースコード

-module(grep).
-compile([export_all]).

filter(Regexp,Lines) ->
    lists:filter(fun (Line) ->
			 case regexp:match(Line,Regexp) of
			     {match,_,_} ->
				 true;
			     _  ->
				 false
			 end
		 end,Lines).

get_lines(Io) ->
    case io:get_line(Io,"") of
	eof ->
	    [];
	S ->
	    [S| get_lines(Io)]
    end.

grep(From,Regexp,Path) ->
    {ok,Io} = file:open(Path,[read]),
    lists:foreach(fun(S) -> io:format("~s:~s",[Path,S]) end,
		  filter(Regexp,get_lines(Io))),
    file:close(Io),
    From ! bye.

loop(0) ->
    bye;
loop(N) ->
    receive
	bye ->
	    loop(N-1)
    end.

main([R|Args]) ->
    S = self(),
    lists:foreach(fun(Path) ->
			  spawn(
			    fun () ->
				    grep(S,R,Path)
			    end)
		  end,
		  Args),
    loop(length(Args)).