Make delicious recipes!

Erlang modules and functions

Below code explains the following features of Erlang:
  1. module
  2. export
  3. function
  4. macro
  5. macro-usage


% the first attribute to declare in a module is the name

% all functions that interface to the outside world must be declared
% the number present after the function name is the number of arguments in the function     
-export([add/2, helloWorld/0, callOthers/2, multiply/2]). 
% function to add 2 numbers
add(Var1, Var2) ->
  Var1 + Var2. 
% function to say the usual - Hello World
helloWorld() ->
  io:format("Hello World~n"). 
% function to show how to call other functions
% also shows multi-line functions
callOthers(X,Y) ->

% Erlang supports macros like #define in c
-define(multiplyMacro(A,B), (A*B)). 
-define(divide(A,B), A/B). 

% Only difference from c is that the macro needs to be called with a ?
multiply(A,B) ->
  ?divide(?multiplyMacro(A,B), ?multiplyMacro(A,B)). 

The above file can be compiled and run in werl.exe as follows:

% compile step
erl> c(hello_world). 

% call some functions
erl> hello_world:add(2,3). 

erl> hello_world:helloWorld().
Hello World

erl> hello_world:callOthers(3,4).
Hello World

erl> hello_world:multiply(3,4).

% see some information about the module just compiled  
erl> hello_world:module_info(). 

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal