Skip to content

Instantly share code, notes, and snippets.

@Ajwah
Created April 4, 2017 00:37
Show Gist options
  • Save Ajwah/1f116f80e527d3a523f81a84678673de to your computer and use it in GitHub Desktop.
Save Ajwah/1f116f80e527d3a523f81a84678673de to your computer and use it in GitHub Desktop.
-module(palin).
-export([distributer/0, distributer/1, client/1, server/1, palin/1, nopunct/1, palindrome/1]).
distributer() ->
distributer({spawn(palin, server, ["A"]), spawn(palin, server, ["B"])}).
distributer({Server1, Server2}) ->
receive
{result, Msg} ->
io:format(Msg),
distributer({Server1, Server2});
{stop} ->
Server1 ! stop,
Server2 ! stop;
Msg ->
Server1 ! {check, self(), Msg},
distributer({Server2, Server1})
end.
server(Name) when is_list(Name) ->
receive
stop ->
io:format(Name ++ " Stopped~n");
{check, Pid, Msg} ->
case palindrome(Msg) of
true ->
Pid ! {result, "Server: " ++ Name ++ " with PID: " ++ pid_to_list(self()) ++ "~n" ++ Msg ++ " is a palindrome~n"};
false ->
Pid ! {result, "Server: " ++ Name ++ " with PID: " ++ pid_to_list(self()) ++ "~n" ++ Msg ++ " is not a palindrome~n"}
end,
server(Name)
end;
server(Pid) when is_pid(Pid) ->
receive
stop ->
io:format("stopped~n");
{check, Msg} ->
case palindrome(Msg) of
true ->
Pid ! {result, Msg ++ " is a palindrome"};
false ->
Pid ! {result, Msg ++ " is not a palindrome"}
end,
server(Pid)
end.
client(ServerPid) ->
receive
{result, Msg} ->
io:format(Msg),
client(ServerPid);
stop ->
ServerPid ! stop;
Msg ->
ServerPid ! {check, self(), Msg},
client(ServerPid)
end.
palindrome(Xs) ->
palin(nocaps(nopunct(Xs))).
nopunct([]) ->
[];
nopunct([X|Xs]) ->
case lists:member(X,".,\ ;:\t\n\'\"") of
true ->
nopunct(Xs);
false ->
[ X | nopunct(Xs) ]
end.
nocaps([]) ->
[];
nocaps([X|Xs]) ->
[ nocap(X) | nocaps(Xs) ].
nocap(X) ->
case $A =< X andalso X =< $Z of
true ->
X+32;
false ->
X
end.
% literal palindrome
palin(Xs) ->
Xs == reverse(Xs).
reverse(Xs) ->
shunt(Xs,[]).
shunt([],Ys) ->
Ys;
shunt([X|Xs],Ys) ->
shunt(Xs,[X|Ys]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment