Created
April 7, 2017 15:18
-
-
Save antoine/3cb110f7ad5cd0ec85cbb91f58cc304a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(palindrome). | |
-export([palindrome_check/1, server/1, serve/1]). | |
-export([server_of_clients/0, serve_client/0]). | |
-export([servers_of_clients/0,servers_balancer/3,many_serve_client/1]). | |
rem_punct(String) -> lists:filter(fun (Ch) -> | |
not(lists:member(Ch,"\"\'\t\n ")) | |
end, | |
String). | |
to_small(String) -> lists:map(fun(Ch) -> | |
case ($A =< Ch andalso Ch =< $Z) of | |
true -> Ch+32; | |
false -> Ch | |
end | |
end, | |
String). | |
palindrome_check(String) -> | |
Normalise = to_small(rem_punct(String)), | |
lists:reverse(Normalise) == Normalise. | |
result_for_human(false) -> | |
"is not a palindrome"; | |
result_for_human(true) -> | |
"is a palindrome". | |
% return the response to the pid provided when creating the server | |
server(Pid) -> | |
spawn(palindrome,serve,[Pid]). | |
serve(Pid) -> | |
receive | |
{check, Potentialpalindrome} -> | |
Pid ! {result, io:format("~p ~p", [Potentialpalindrome, result_for_human(palindrome_check(Potentialpalindrome))])}, | |
serve(Pid); | |
stop -> | |
io:format("stop") | |
end. | |
% return the response to the pid provided in the request | |
server_of_clients() -> | |
spawn(palindrome,serve_client,[]). | |
serve_client() -> | |
receive | |
{check, Pid, Potentialpalindrome} -> | |
Pid ! {result, io:format("~p ~p", [Potentialpalindrome, result_for_human(palindrome_check(Potentialpalindrome))])}, | |
serve_client(); | |
stop -> | |
io:format("stop") | |
end. | |
% replicated servers returning the response to the pid provided in the request | |
% ManyServers = palindrome:servers_of_clients(). | |
% ManyServers ! {check, self(), "AaaaA"}. | |
% ManyServers ! {check, self(), "AaadddaA"}. | |
% ManyServers ! stop. | |
servers_of_clients() -> | |
First = spawn(palindrome, many_serve_client, ["server1"]), | |
spawn(palindrome,servers_balancer,[First, | |
First, | |
spawn(palindrome, many_serve_client, ["server2"]) | |
]). | |
next_server(X,X,Y) -> | |
Y; | |
next_server(Y,X,Y) -> | |
X. | |
servers_balancer(Next, Server1, Server2) -> | |
receive | |
stop -> | |
Server1 ! stop, | |
Server2 ! stop; | |
Msg -> Next ! Msg | |
end, | |
servers_balancer(next_server(Next, Server1, Server2), Server1, Server2). | |
many_serve_client(Name) -> | |
receive | |
{check, Pid, Potentialpalindrome} -> | |
Pid ! {result, io:format("~p: ~p ~p", [Name, Potentialpalindrome, result_for_human(palindrome_check(Potentialpalindrome))])}, | |
many_serve_client(Name); | |
stop -> | |
io:format("stop") | |
end. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment