questions: http://www.erlang.org/course/exercises.html
my answers:
%1.
temp_f2c(F) -> 5*(F-32) div 9.
temp_c2f(C) -> 9*C div 5 + 32.
%2.
temp_convert({c,X}) -> {f, temp_c2f(X)};
temp_convert({f,X}) -> {c, temp_f2c(X)}.
%3.
mathStuff_perimeter({square, Side}) -> 4*Side;
mathStuff_perimeter({circle, Radius}) -> 2*3.14*Radius;
mathStuff_perimeter({triangle, A, B, C}) -> A + B + C.
%1.
lists1_min([H | R]) -> lists1_min(R, H).
lists1_min([], Result) -> Result;
lists1_min([H | R], Result) -> lists1_min(R, erlang:min(H, Result)).
%2.
lists1_max([H | R]) -> lists1_max(R, H).
lists1_max([], Result) -> Result;
lists1_max([H | R], Result) -> lists1_max(R, erlang:max(H, Result)).
%3.
lists1_min_max(L) -> {lists1_min(L), lists1_max(L)}.
%4.
listR2([_, _, C, D]) -> [C, D];
listR2([C, D]) -> [C, D];
listR2([D]) -> [48, D].
time_swedish_date() ->
{Y, M, D} = date(),
listR2(integer_to_list(Y)) ++ listR2(integer_to_list(M)) ++ listR2(integer_to_list(D)).
%1.
%2.
start(N, M, Msg) ->
% 创建进程N
PN = spawn(?MODULE, ring, [N, N, self()]),
receive
after 100 ->
% 把消息发给进程N
PN ! {Msg, M}
end.
% 创建进程
ring(0, _, _) ->
nil;
ring(N, N, _) ->
io:format("P~p run~n", [N]),
PN = self(),
Pnext = spawn(?MODULE, ring, [N - 1, N, PN]),
loop(N, N, PN, Pnext);
ring(I, N, PN) ->
io:format("P~p run~n", [I]),
Pnext = spawn(?MODULE, ring, [I - 1, N, PN]),
loop(I, N, PN, Pnext).
% 消息循环
loop(1, N, PN, Pnext) ->
receive
{Msg, Mi} ->
io:format("~p recv msg ~p~n", [1, Mi]),
% 进程1把接受到的消息发给进程N
PN ! {Msg, Mi},
loop(1, N, PN, Pnext);
_ -> nil
end;
loop(N, N, PN, Pnext) ->
receive
{_, 0} ->
io:format("~p recv msg 0~n", [N]),
% 进程N接受到最后一个消息,发stop消息
Pnext ! stop;
{Msg, Mi} ->
io:format("~p recv msg ~p~n", [N, Mi]),
Pnext ! {Msg, Mi - 1},
loop(N, N, PN, Pnext)
end;
loop(Pi, N, PN, Pnext) ->
receive
{Msg, Mi} ->
io:format("~p recv msg ~p~n", [Pi, Mi]),
Pnext ! {Msg, Mi},
loop(Pi, N, PN, Pnext);
_ -> nil
end.
运行结果:
x:start(3,5, msg).
P3 run
P2 run
P1 run
3 recv msg 5
{msg,5}
2 recv msg 4
1 recv msg 4
3 recv msg 4
2 recv msg 3
1 recv msg 3
3 recv msg 3
2 recv msg 2
1 recv msg 2
3 recv msg 2
2 recv msg 1
1 recv msg 1
3 recv msg 1
2 recv msg 0
1 recv msg 0
3 recv msg 0
%3.