Skip to content

Instantly share code, notes, and snippets.

@unaipme
Last active February 18, 2019 15:24
Show Gist options
  • Save unaipme/5269d566586d3f8ad00b7e68b2754d74 to your computer and use it in GitHub Desktop.
Save unaipme/5269d566586d3f8ad00b7e68b2754d74 to your computer and use it in GitHub Desktop.
First encounter with Erlang
-module(dates).
-author("unai").
%% API
-export([classify_day/1]).
classify_day({saturday}) -> classify_day({weekend});
classify_day({sunday}) -> classify_day({weekend});
classify_day({weekend}) -> weekend;
classify_day({_}) -> weekday.
-module(geometry).
-author("unai").
%% API
-export([area/1]).
area({rectangle, Width, Height}) -> Width * Height;
area({circle, Radius}) -> 3.14159 * Radius * Radius;
area({square, Side}) -> Side * Side.
-module(main).
-author("unai").
-export([main/0, server/0]).
-import(geometry, [area/1]).
-import(dates, [classify_day/1]).
-import(myfactorial, [factorial/1]).
-import(io, [fwrite/2, fwrite/1]).
main() ->
fwrite("Hello, world!~n"),
%Area = area({rectangle, 10, 4}),
%fwrite("The area of a rectangle of 10x4 is ~w~n", [area({rectangle, 10, 4})]),
fwrite("Sunday is the ~w and thursday is ~w~n", [classify_day({sunday}), classify_day({thursday})]),
fwrite("The factorial of 4 is ~w and of 8 is ~w~n", [factorial(4), factorial(8)]),
Pid = spawn(fun() -> server() end),
Pid ! {self(), {rectangle, 6, 10}},
receive N -> fwrite("Rectangle's area is ~w~n", [N]) end,
fwrite("Circle's area is ~w~n", [rpc(Pid, {circle, 5})]).
server() ->
receive
{From, {rectangle, Width, Height}} ->
Area = Width * Height,
%fwrite("The area of the rectangle is ~w~n", [Area]),
From ! Area,
server();
{From, {circle, Radius}} ->
Area = 3.14159 * Radius * Radius,
%fwrite("The area of the circle is ~w~n", [Area]),
From ! Area,
server();
{From, Request} ->
%fwrite("I don't know how to calculate that :(~n"),
From ! {error, Request},
server()
end.
rpc(Pid, Request) ->
Pid ! {self(), Request},
receive
{Pid, Response} ->
Response
end.
-module(myfactorial).
-author("unai").
%% API
-export([factorial/1]).
factorial(N) when N > 1 -> N * factorial(N - 1);
factorial(_) -> 1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment