/
turnstile2.erl
62 lines (51 loc) · 1.09 KB
/
turnstile2.erl
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
%%
%% Erlang Programming, p.125.
%% FSM Pattern.
%%
%% 1> turnstile2:start().
%% 2> turnstile2:coin().
%% 3> turnstile2:coin().
%% 4> turnstile2:pass().
%% 5> turnstile2:pass().
%% 6> turnstile2:stop().
%%
-module(turnstile2).
-export([start/0, stop/0]).
-export([coin/0, pass/0]).
-export([init/0]).
% Start/stop functions
start() -> register(turnstile2, spawn(?MODULE, init, [])).
stop() -> turnstile2 ! stop.
% Initial state
init() -> locked().
% Events
coin() -> turnstile2 ! coin.
pass() -> turnstile2 ! pass.
% States and transitions
locked() ->
receive
pass ->
alarm(),
locked();
coin ->
unlock(),
unlocked();
stop ->
ok
end.
unlocked() ->
receive
pass ->
lock(),
locked();
coin ->
thankyou(),
unlocked();
stop ->
ok
end.
% Actions
alarm() -> io:format("You shall not pass!~n").
unlock() -> io:format("Unlocking...~n").
lock() -> io:format("Locking...~n").
thankyou() -> io:format("Thank you for donation~n").