Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

An Example from [Concurrent Programming in Erlang]

  • Loading branch information...
commit 1b8f0824924d8d9e8636cb2024bb502eb155a325 1 parent b76f0cc
@hiroprotagonist authored
View
1  .gitignore
@@ -0,0 +1 @@
+*.beam
View
20 Bankserver/bank_client.erl
@@ -0,0 +1,20 @@
+-module(bank_client).
+-export([ask/1, deposit/2, withdraw/2]).
+
+head_office() -> 'bank@io.s3.abas.de'.
+
+ask(Who) -> call_bank({ask, Who}).
+deposit(Who, Amount) -> call_bank({deposit, Who, Amount}).
+withdraw(Who, Amount) -> call_bank({withdraw, Who, Amount}).
+
+call_bank(Msg) ->
+ Headoffice = head_office(),
+ monitor_node(Headoffice, true),
+ {bank_server, Headoffice} ! {self(), Msg},
+ receive
+ {bank_server, Reply} ->
+ monitor_node(Headoffice, false),
+ Reply;
+ {nodedown, Headoffice} ->
+ no
+ end.
View
43 Bankserver/bank_server.erl
@@ -0,0 +1,43 @@
+-module(bank_server).
+-export([start/0, server/1]).
+
+%% Spawn bank_server process.
+%% To prevent repeated starts the process is registered under the name "bank_server"
+start() ->
+ register(bank_server, spawn(bank_server, server, [[]])).
+
+%% Main Server loop
+server(Data) ->
+ receive
+ {From, {deposit, Who, Amount}} ->
+ From ! {bank_server, ok},
+ server(deposit(Who, Amount, Data));
+ {From, {ask, Who}} ->
+ From ! {bank_server, lookup(Who, Data)},
+ server(Data);
+ {From, {withdraw, Who, Amount}} ->
+ case lookup(Who, Data) of
+ undefined ->
+ From ! {bank_server, no},
+ server(Data);
+ Balance when Balance > Amount ->
+ From ! {bank_server, ok},
+ server(deposit(Who, -Amount, Data));
+ _ ->
+ From ! {bank_server, no},
+ server(Data)
+ end
+ end.
+
+%% Business logic goes here
+lookup(Who, [{Who, Value}|_]) -> Value;
+lookup(Who, [_|T]) -> lookup(Who, T);
+lookup(_, _) -> undefined.
+
+deposit(Who, X, [{Who, Balance}|T]) ->
+ [{Who, Balance+X}|T];
+deposit(Who, X, [H|T]) ->
+ [H|deposit(Who, X, T)];
+deposit(Who, X, []) ->
+ [{Who, X}].
+
Please sign in to comment.
Something went wrong with that request. Please try again.