Last active
April 5, 2017 02:43
-
-
Save calopez/1c375932829d88898a55d51b1e86d072 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(palin). | |
| -export([ | |
| palin/1, | |
| nopunct/1, | |
| palindrome/1, | |
| client/0, | |
| server/0 | |
| ]). | |
| % palindrome problem | |
| % | |
| % palindrome("Madam I\'m Adam.") = true | |
| 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]). | |
| %% ------- | |
| %% Client | |
| %% ------- | |
| client() -> | |
| receive | |
| {send, Pid, Msg} -> | |
| Pid ! Msg; | |
| {result, Msg } -> | |
| io:format("client received: ~p~n", [Msg]), | |
| client(); | |
| stop -> | |
| io:format("client stopped!") | |
| end. | |
| %% ------- | |
| %% Server | |
| %% ------- | |
| server() -> | |
| Workers = palin_workers(), | |
| receive | |
| {check, Client, Payload} -> | |
| lb(Workers, Client, Payload), | |
| server(); | |
| stop -> io:format("stopped ~n") | |
| end. | |
| lb(Workers, Client, Payload) when is_pid(Client) -> | |
| Worker = element(rand:uniform(2), Workers), | |
| Worker ! {Client, Payload}. | |
| palin_workers() -> | |
| { | |
| spawn(fun worker1/0), | |
| spawn(fun worker2/0) | |
| }. | |
| worker1() -> | |
| receive | |
| {Client, Payload} -> | |
| io:format("response from Sever 1!~n"), | |
| Client ! response(Payload) | |
| end. | |
| worker2() -> | |
| receive | |
| {Client, Payload} -> | |
| io:format("response from Sever 2!~n"), | |
| Client ! response(Payload) | |
| end. | |
| response(String) -> | |
| Is = palindrome(String), | |
| Be = if Is =:= true -> " is "; | |
| true -> " is not " | |
| end, | |
| {result, lists:flatten([$", String, $", Be, "palindrome"])}. | |
| %% ------ | |
| %% Usage | |
| %% ------ | |
| %% 1> Server = spawn(palin, server, []). | |
| %% 2> Client = spawn(palin, client, []). | |
| %% 3> Server ! {check, Client, "Air an aria"}. | |
| %% 4> Server ! {check, self(), "Air an aria"}. | |
| %% 5> flush(). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment