1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
-module(l).
-export([loop/1,
rev/1,
length/1,
times/3,
start_pong/1,
pong/1,
r/0,
start_pong2/1,
start_pong3/0,
pong/0,
version/0
]).
%%%%%%%%% Sum it up %%%%%%%%%%%%%%%%%%%
loop(X) -> loop(X, 0).
loop(_X=0, Sum) -> Sum;
loop(X, Sum) -> loop(X-1, Sum+X).
%%%%%%%%% Reverse a list %%%%%%%%%%%%%%
rev(L) -> rev(L, []).
rev([], N) -> N;
rev([H|T], N) -> rev(T, [H] ++ N).
%%%%%%%%%% Length of a list %%%%%%%%%%%
length(L) -> length(L, 0).
length([], N) -> N;
length([_H|T], N) -> length(T, N+1).
%%%%%%%%%% Run Fun X tmes %%%%%%%%%%%%
times(_F, _Args, 0) -> ok;
times(F, Args, X) ->
F(Args),
times(F, Args, X-1).
%%%%%%%%%% Echo message sent %%%%%%%%%
start_pong(Pid) ->
spawn(l, pong, [Pid]).
pong(Pid) ->
receive
giveup ->
io:format("Pong finished~n", []);
{ping, Msg} ->
io:format("pong: Received ping '~s'~n", [Msg]),
Pid ! {pong, Msg},
pong(Pid);
Msg ->
io:format("Unknwown message ~p, giving up", [Msg]),
exit(reason)
end.
r() ->
receive X -> X end.
%%%%%%%%% Linked ping %%%%%%%%%%%%%%%
start_pong2(Pid) ->
P = spawn(l, pong, [Pid]),
link(P),
P.
%%%%%%%%% Distributed ping %%%%%%%%%%
start_pong3() ->
P = spawn(l, pong, []),
register(pong, P),
P.
pong() ->
receive
giveup ->
io:format("Pong finished~n", []);
{ping, Msg, Pid} ->
io:format("ping: Received ping '~s' from '~p~n", [Msg, Pid]),
Pid ! {pong, Msg},
pong();
Msg ->
io:format("Unknwown message ~p, giving up", [Msg]),
exit(reason)
end.
%%%%%%%%% Code replacement %%%%%%%%%%%%%%%
version() ->
io:format("This is version 1").
|