c(translate_service).
c(doctor_translate).
Doctor = spawn(fun doctor_translate:watch/0).
Doctor ! new.
translate_service:translate(translator, "casa").
translate_service:translate(translator, "blanca").
translate_service:translate(translator, "incorrect").
translate_service:translate(translator, "casa").
Created
April 6, 2017 21:49
-
-
Save iain17/250e5030f75a03edaa73e9237c0cd1ec 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(doctor_translate). | |
-export([loop/0, watch/0]). | |
%Assignments: | |
%Make the Doctor process restart itself if it should die. | |
%+ | |
%Make a monitor for the Doctor monitor. If either monitor dies, restart it. | |
loop() -> | |
process_flag(trap_exit, true), | |
receive | |
new -> | |
io:format("Creating and monitoring process.~n"), | |
register(translator, spawn_link(fun translate_service:loop/0)), | |
loop(); | |
{'EXIT', From, Reason} -> | |
io:format("The translate service ~p died with reason ~p.~n", [From, Reason]), | |
io:format("Restarting... ~n"), | |
self() ! new, | |
loop() | |
end. | |
watch() -> | |
process_flag(trap_exit, true), | |
receive | |
new -> | |
io:format("Creating and monitoring new Doctor process.~n"), | |
register(doctor, spawn_link(fun loop/0)), | |
doctor ! new, | |
watch(); | |
{'EXIT', From, Reason} -> | |
io:format("The translate service doctor ~p died with reason ~p.~n", [From, Reason]), | |
io:format("Restarting... ~n"), | |
self() ! new, | |
watch() | |
end. |
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
% Based on: https://media.pragprog.com/titles/btlang/code/erlang/translate_service.erl | |
-module(translate_service). | |
-export([loop/0, translate/2]). | |
%Assignment: Monitor the translate_service and restart it should it die. | |
loop() -> | |
receive | |
{From, "casa"} -> | |
From ! "house", | |
loop(); | |
{From, "blanca"} -> | |
From ! "white", | |
loop(); | |
{From, _} -> | |
From ! "I don't understand.", | |
exit("Undefined word.") | |
end. | |
translate(To, Word) -> | |
To ! {self(), Word}, | |
receive | |
Translation -> Translation | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment