Skip to content

Instantly share code, notes, and snippets.

@cr0t
Created July 27, 2022 16:10
Show Gist options
  • Save cr0t/c534fef2d201a57342ffc758aa67f42d to your computer and use it in GitHub Desktop.
Save cr0t/c534fef2d201a57342ffc758aa67f42d to your computer and use it in GitHub Desktop.
Universal Server ("My favorite Erlang Program")
% Read more:
% - https://joearms.github.io/published/2013-11-21-My-favorite-erlang-program.html
% - https://ferd.ca/my-favorite-erlang-container.html
%
% How to run:
% $ erl
% > c(uni).
% {ok,uni}
% > uni:test().
% 30414093201713378043612608166064768844377641568960512000000000000
-module(uni).
-export([test/0]).
test() ->
Pid = spawn(fun universal_server/0),
Pid ! {become, fun factorial_server/0},
Pid ! {self(), 50},
receive
X -> X
end.
universal_server() ->
receive
{become, F} ->
F()
end.
factorial_server() ->
receive
{From, N} ->
From ! factorial(N),
factorial_server()
end.
factorial(0) -> 1;
factorial(N) -> N * factorial(N - 1).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment