diff options
author | Trygve Laugstøl <trygvis@inamo.no> | 2024-02-23 07:08:18 +0100 |
---|---|---|
committer | Trygve Laugstøl <trygvis@inamo.no> | 2024-02-23 07:08:18 +0100 |
commit | 5a9cdd3cc89507d4d74f8bded56ce5e037b3b56e (patch) | |
tree | 982ca2e7f9ac4e8c350dfb5c4f60bcfdfff5afaf /learn-you-some-erlang/kitty_server2.erl | |
parent | 05ae56e5e89abf2993f84e6d52b250131f247c35 (diff) | |
download | erlang-workshop-5a9cdd3cc89507d4d74f8bded56ce5e037b3b56e.tar.gz erlang-workshop-5a9cdd3cc89507d4d74f8bded56ce5e037b3b56e.tar.bz2 erlang-workshop-5a9cdd3cc89507d4d74f8bded56ce5e037b3b56e.tar.xz erlang-workshop-5a9cdd3cc89507d4d74f8bded56ce5e037b3b56e.zip |
wip
Diffstat (limited to 'learn-you-some-erlang/kitty_server2.erl')
-rw-r--r-- | learn-you-some-erlang/kitty_server2.erl | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/learn-you-some-erlang/kitty_server2.erl b/learn-you-some-erlang/kitty_server2.erl new file mode 100644 index 0000000..b2acbb2 --- /dev/null +++ b/learn-you-some-erlang/kitty_server2.erl @@ -0,0 +1,49 @@ +%%%%% Abstracted version +-module(kitty_server2). + +-export([start_link/0, order_cat/4, return_cat/2, close_shop/1]). +-export([init/1, handle_call/3, handle_cast/2]). + +-record(cat, {name, color=green, description}). + +%%% Client API +start_link() -> my_server:start_link(?MODULE, []). + +%% Synchronous call +order_cat(Pid, Name, Color, Description) -> + my_server:call(Pid, {order, Name, Color, Description}). + +%% This call is asynchronous +return_cat(Pid, Cat = #cat{}) -> + my_server:cast(Pid, {return, Cat}). + +%% Synchronous call +close_shop(Pid) -> + my_server:call(Pid, terminate). + +%%% Server functions +init([]) -> []. %% no treatment of info here! + +handle_call({order, Name, Color, Description}, From, Cats) -> + if Cats =:= [] -> + my_server:reply(From, make_cat(Name, Color, Description)), + Cats; + Cats =/= [] -> + my_server:reply(From, hd(Cats)), + tl(Cats) + end; + +handle_call(terminate, From, Cats) -> + my_server:reply(From, ok), + terminate(Cats). + +handle_cast({return, Cat = #cat{}}, Cats) -> + [Cat|Cats]. + +%%% Private functions +make_cat(Name, Col, Desc) -> + #cat{name=Name, color=Col, description=Desc}. + +terminate(Cats) -> + [io:format("~p was set free.~n",[C#cat.name]) || C <- Cats], + exit(normal). |