Erlang
Erlang is a functional programming language. A good tutorial is available here.
Calculating Pi
Export a module for it to be used from other files by using -module(<name>)
.
Similarly, export function definitions as -export([<func_name>/<num_params>])
.
-module(pi).
-export([pi/0]). % export pi/0 for calculation using 4 * pi/3 as below
-export([pi/3]). % export pi/3 for testing.
pi() -> 4 * pi(0,1,1).
pi(Initial,Sign,SeriesDivisor) ->
TaylorValue = 1 / SeriesDivisor,
if
% first check TaylorValue > precision. If it is, then we haven't reached
% the appropriate precision, so we must keep recursing the function.
TaylorValue > 0.000001 ->
pi(Initial+(Sign*TaylorValue), Sign*-1, SeriesDivisor+2);
% if the check above was not true, then `true` when always return, so we return T.
true ->
Initial
end.
Finding unique elements of a list
The function below removes all elements from the list that are already on the list.
-module (unique).
-export ([unique/1]).
unique([H|L]) ->
unique([X || X <- L, X < H]) ++ [H] ++ unique([X || X <- L, X > H]);
unique([]) -> [].
It is also magic for me.
Communication between processes
A process can spawn another process like so:
NewProcessPid = spawn(?MODULE, functionname, [arg1, arg2]).
Then, a process can communicate with the new process like so:
NewProcessPid ! message.
A process can access its own Process ID by calling the self()
function.