Today, we are going to write a function to compute the distance between two points in the cartesian plane.
We’ll call our module calculus.
-module(calculus).
A point in the cartesian plane has two coordinates X and Y, so we’ll need a function handling 4 parameters, and then the interface will be:
-export([modulus/4]).
Using the Pythagoras Theorem, the distance between two points is computed as the square root of the sum of the squared differences between the coordinates.
Erlang provides a math library to perform mathematical function, the square root function can be called using math:sqrt().
So our function will look like:
distance(X0, Y0, X1, Y1) -> math:sqrt(((X1-X0)*(X1-X0)+(Y1-Y0)*(Y1-Y0))).
The full source code for the calculus.erl file will be
-module(calculus).
-export([distance/4]).
distance(X0, Y0, X1, Y1) -> math:sqrt(((X1-X0)*(X1-X0)+(Y1-Y0)*(Y1-Y0))).
now let’s compile and run the program
47> c(calculus).
{ok,calculus}
48> calculus:distance(0,0,3,4).
5.0
49>
Gg1