Created
April 5, 2017 17:24
-
-
Save mattludwigs/aa52011dc0c6ce43abd3e1e99a7cb994 to your computer and use it in GitHub Desktop.
Week 1 - Process and Messages (futurelearn.com)
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(palin). | |
-compile(export_all). | |
% Starting a single server % | |
% erl> Pid = palin:start(). | |
% erl> palin:check_palindrome(Pid, "bob"). | |
% true | |
% | |
% Start multi server % | |
% erl> Pid = palin:start(5). | |
% erl> palin:check_palindrome(Pid, "bob"). | |
% true | |
% == Client == | |
start() -> spawn(?MODULE, server, []). | |
start(N) -> lb_start(N). | |
check_palindrome(Pid, String) -> | |
Pid ! {self(), {check, String}}, | |
receive | |
true -> | |
io:format("~p is a palindrome~n", [String]); | |
false -> | |
io:format("~p is not a palindrome~n", [String]) | |
end. | |
% == Server == | |
server() -> | |
receive | |
{From, {check, Msg}} -> | |
From ! palindrome(Msg), | |
server(); | |
_ -> | |
io:format("Stopping~n") | |
end. | |
server(0) -> | |
io:format("Must pass number of servers to start"); | |
server(N) -> | |
lists:map(fun (_) -> start() end, lists:seq(1, N)). | |
% Load Balancer (Not really but just using many workers and sends work them in order) | |
% Would normally move to its own module | |
lb_start(N) -> | |
Workers = server(N), | |
spawn(?MODULE, lb, [Workers]). | |
lb([WorkerPid | Workers]) -> | |
receive | |
stop -> | |
stop; | |
Msg -> | |
WorkerPid ! Msg, | |
lb(Workers ++ [WorkerPid]) | |
end. | |
% palindrome problem | |
% | |
% palindrome("Madam I\'m Adam.") = true | |
% Code below is provide via the https://www.futurelearn.com/courses/concurrent-programming-erlang course | |
% to get students some base code to wrap in processes. | |
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