summaryrefslogtreecommitdiff
path: root/l.erl
diff options
context:
space:
mode:
authorGuido Günther <agx@sigxcpu.org>2016-05-10 17:19:15 +0200
committerGuido Günther <agx@sigxcpu.org>2016-05-10 17:19:15 +0200
commit54ba43b15f6875e1d65ebed772c5dd678bb4752c (patch)
tree3734e223934863eb9be63f8d549a10b292d450da /l.erl
Initial commit
Diffstat (limited to 'l.erl')
-rw-r--r--l.erl104
1 files changed, 104 insertions, 0 deletions
diff --git a/l.erl b/l.erl
new file mode 100644
index 0000000..b33c650
--- /dev/null
+++ b/l.erl
@@ -0,0 +1,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").