Erlang并发编程:从基础到实践
1. 简单示例
在Erlang中,我们可以将函数以进程的形式来重写。例如,之前定义的 area/1
函数:
area({rectangle, Width, Ht}) -> Width * Ht;
area({circle, R}) -> 3.14159 * R * R.
现在将其重写为一个进程:
-module(area_server0).
-export([loop/0]).
loop() ->
receive
{rectangle, Width, Ht} ->
io:format("Area of rectangle is ~p~n",[Width * Ht]),
loop();
{circle, R} ->
io:format("Area of circle is ~p~n", [3.14159 * R * R]),
loop();
Other ->
io:format("I don't know what the area of a ~p is ~n",[Other]),
loop()
end.
在shell中,我们可以创建一个进程来执行 loop/0 </