2007/05/19

Erlang クエックブックにインデックスを付ける。プロセスバージョン。

やっぱりプロセスを使わないと。


-module(make_index).
-compile(export_all).

start() ->
lists:foreach(fun(X) -> register(X, spawn_link(?MODULE, holder, [[]])) end,
[head, tail, index]),
register(contents, spawn_link(?MODULE, contents, [head])),
{ok, In} = file:read_file("cookbook_src.html"),
loop(binary_to_list(In)).

holder(V) ->
receive
{get, From} ->
From ! lists:reverse(V);
X ->
holder([X|V])
end.

contents(HorT) ->
receive
tail ->
contents(tail);
'終ったよ' ->
file:write_file("cookbook.html",
[begin
P ! {get, self()},
receive X -> X end
end || P <- [head, index, tail]]);
X ->
HorT ! X,
contents(HorT)
end.

loop([]) ->
contents ! '終ったよ';
loop("****index_place****" ++ T) ->
contents ! tail,
loop(T);
loop("<h2>" ++ T) ->
[Ast|Ref] = erlang:ref_to_list(make_ref()),
index ! io_lib:format("<h3><a href='~s'>", [[Ast|Ref]]),
contents ! io_lib:format("<h2><a name='~s'>", [Ref]),
h2(T);
loop("<h3>" ++ T) ->
[Ast|Ref] = erlang:ref_to_list(make_ref()),
index ! io_lib:format("<a href='~s'>", [[Ast|Ref]]),
contents ! io_lib:format("<h3><a name='~s'>", [Ref]),
h3(T);
loop([X|T]) ->
contents ! X,
loop(T).

h2("</h2>" ++ T) ->
index ! "</a></h3>",
contents ! "</a></h2>",
loop(T);
h2([X|T]) ->
index ! X,
contents ! X,
h2(T).

h3("</h3>" ++ T) ->
index ! "</a><br>",
contents ! "</a></h3>",
loop(T);
h3([X|T]) ->
index ! X,
contents ! X,
h3(T).

0 件のコメント: