|
||||||
Create and Use Erlang Modules and FunctionsHow to Reuse Ericsson Erlang Code in Multiple ApplicationsRather that typing in the same code everytime that they start a new shell, the Erlang programmer can store all of their functions in a module and then use and reuse their
The article Get Started with the Erlang Programming Language is a brief introduction to Erlang and discusses how to:
However, there is a limitation to that, and it's the fact that all of the code has to be retyped every time that a shell is started. Fortunately the solution is quite simple, and that's to:
The first step is, therefore, to create an Erlang module. Creating an Erlang ModuleAn Ericsson Erlang module is, quite simply, a text file. And the minimal module always contains a module header: -module(circle).
Here the module is to be named "circle". The only constraints at this point are that:
In this example, therefore, the file name will be "circle.erl". Creating an Erlang FunctionThe next stage is to add functionality to the module. This will consist of a number of functions that the programmer will call from the Erlang shell once the module has been loaded. The function definition consists of two steps:
The export statement must always come before the function definitions, for example: -export([circumference/1]).
pi() -> 3.14159265358979.
circumference(R) -> 2 * pi()* R.
In this example:
Once this code has been saved into "circle.erl" then it is ready for use in the Erlang shell. Loading an Erlang ModuleThe module can no be accessed if:
It can then be loaded by using the c method: c (circle).
Remembering, of course, that every line must be terminated with a full stop (or period). This will load the module (as seen in figure 1 at the bottom of this article), and then any exported functions will be available to the user. Using Functions from an Erlang ModuleWith the module loaded, the programmer can access its functions, for example: circle:circumference (2.5).
This (as can be seen in figure 2) will return 15.70796326794895, but any attempt to access the pi function will result in a error (because that is private and can only be used by the circumference function). The programmer can now go on to create more complex Erlang applications and will be able to reuse their code wherever it is required.
The copyright of the article Create and Use Erlang Modules and Functions in Computer Programming Tutorials is owned by Mark Alexander Bain. Permission to republish Create and Use Erlang Modules and Functions in print or online must be granted by the author in writing.
|
||||||
|
|
||||||
|
|
||||||