Created
June 29, 2020 06:28
-
-
Save yuanjs/76d74e31785da30425ed54bf649a3fc6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(palinserver). | |
-export([start/0, server_stop/1, serverloop/1, processloop/0, check_palin/2]). | |
%% start 5 processloop to process the request of palindrome check | |
%% then start the server to listen request | |
start() -> | |
ServerList = [spawn(palinserver, processloop, []) || _S <- lists:seq(1, 5)], | |
spawn(palinserver, serverloop, [ServerList]). | |
%% select random processloop to do the check job | |
%% if receive stop signal, stop all the processloop | |
serverloop(ServerList) -> | |
ProcessId = lists:nth(rand:uniform(5), ServerList), | |
receive | |
{Client, check, Msg} -> | |
ProcessId ! {Client, check, Msg}, | |
serverloop(ServerList); | |
{Client, stop } -> | |
[S ! {Client, stop} || S <- ServerList] | |
end. | |
%% process doing the check job | |
processloop() -> | |
receive | |
{Client, check, Msg} -> | |
case palindrome_check(Msg) of | |
true -> | |
Client ! {self(), result, io_lib:format("\"~s\" is a palindrome", [Msg])}; | |
false -> | |
Client ! {self(), result, io_lib:format("\"~s\" is not a palindrome", [Msg])} | |
end, | |
processloop(); | |
{_Client, stop} -> | |
io:format("Server Stop~n") | |
end. | |
%%stop the server and the process | |
server_stop(Server) -> | |
Server ! {self(), stop}. | |
%% export function for check palindrome string | |
check_palin(Server, Msg) -> | |
Server ! {self(), check, Msg}, | |
receive | |
{Pid, result, Str} -> | |
io:format("ProcessID: ~p ~s~n", [Pid, Str]) | |
end. | |
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great code! A few tests would be a nice addition to it :)