2016年6月20日月曜日

開発環境

7つの言語 7つの世界 (Bruce A. Tate (著)、まつもとゆきひろ (監訳)、田和 勝 (翻訳)、オーム社)の第6章(Erlang)、6.4(3日目: 赤い錠剤(The Red Pill))、セルフスタディ3日目を取り組んでみる。

セルフスタディ3日目(翻訳サービス).

コード(Emacs)

-module(translate_service).
-export([loop/0, translate/2]).
            
loop() ->
    receive {From, "casa"} ->
            From ! "house",
            loop();
            {From, "blanca"} ->
            From ! "white",
            loop();
            {From, _}  ->
            From ! "I don't understand.",
            exit({translater, service, die, at, erlang:time()})
end.

translate(To, Word) ->
    To ! {self(), Word},
    receive Translateion ->
            Translateion
end.

-module(translate_service_monitor).
-export([loop/0]).

loop() ->
    process_flag(trap_exit, true),    
    receive new ->
            io:format("Creating and monitoring process.~n"),
            register(translator, spawn_link(fun translate_service:loop/0)),
            loop();
            {'EXIT', From, Reason}  ->
            io:format("The ~p died with reason ~p.", [From, Reason]),
            self() ! new,
            loop()
end.

入出力結果(Terminal, REPL(Read, Eval, Print, Loop))

$ erl
Eshell V7.3  (abort with ^G)
1> c(translate_service_monitor).
{ok,translate_service_monitor}
2> Monitor = spawn(fun translate_service_monitor:loop/0).
<0.39.0>
3> Monitor ! new.
Creating and monitoring process.
new
4> c(translate_service).
{ok,translate_service}
5> translate_service:translate(translator, "casa").
"house"
6> translate_service:translate(translator, "blanca").
"white"
7> translate_service:translate(translator, "erlang").
The <0.41.0> died with reason {translater,service,die,at,{15,36,37}}.Creating and monitoring process.
"I don't understand."
8> translate_service:translate(translator, "casa").
"house"
9> translate_service:translate(translator, "erlang").
The <0.50.0> died with reason {translater,service,die,at,{15,36,46}}.Creating and monitoring process.
"I don't understand."
10> translate_service:translate(translator, "blanca").
"white"
11> translate_service:translate(translator, "erlang").
The <0.53.0> died with reason {translater,service,die,at,{15,36,54}}.Creating and monitoring process.
"I don't understand."
12> translate_service:translate(translator, "erlang").
The <0.56.0> died with reason {translater,service,die,at,{15,36,56}}.Creating and monitoring process.
"I don't understand."
13> *** Terminating erlang (nonode@nohost)
$

0 コメント:

コメントを投稿