?

Log in

No account? Create an account

Previous Entry | Next Entry

11> c("/home/jinkee/PhD_work/trunk/code/erlang_tutorial/joe_armstrong_programming_erlang/problems/chapter8/an\
swer1", [{outdir, "/home/jinkee/PhD_work/trunk/code/erlang_tutorial/joe_armstrong_programming_erlang/problems\
/chapter8/"}]).
{ok,answer1}
12> answer1:run(blah,3).
registered atom blah to proc <0.78.0> at time {1248,965105,974033}, now is <0.78.0>
cannot register atom blah to proc <0.79.0> at time {1248,965105,974132}, now is <0.78.0>
cannot register atom blah to proc <0.80.0> at time {1248,965105,974213}, now is <0.78.0>
cannot register atom blah to proc <0.81.0> at time {1248,965105,974289}, now is <0.78.0>
[ok,ok,ok,ok]


answers to chapter 8 question 1 under the cut


-module(answer1).
-export([
run/2,
start/2,
for/3
]).
%% http://www.trapexit.org/Category:DateTimeRecipes
run(Atom, N)->
for(0,N, fun()->start(Atom,fun()-> loop()end) end).

start(Atom, Fun)->
P = spawn(Fun),
case is_pid(whereis(Atom)) of
false ->
register(Atom,P),
io:format(
"registered atom ~p to proc ~p at time ~p, now is ~p~n",
[
Atom, P, erlang:now(), whereis(Atom)
]
);
true->
io:format(
"cannot register atom ~p to proc ~p at time ~p, now is ~p~n",
[
Atom, P, erlang:now(), whereis(Atom)
]
)%,
%exit(already_registered)
end.

loop()->
loop().





%% for loop utility
for(N,N,Fun)->
[Fun()];
for(I,N,Fun) ->
[Fun()|for(I+1,N,Fun)].