|
Erlang modules and functionsBelow code explains the following features of Erlang:
hello_world.erl: % the first attribute to declare in a module is the name -module(hello_world). % 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) -> helloWorld(), add(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). {ok,hello_world} % call some functions erl> hello_world:add(2,3). 5 erl> hello_world:helloWorld(). Hello World ok erl> hello_world:callOthers(3,4). Hello World 7 erl> hello_world:multiply(3,4). 1.0 % see some information about the module just compiled erl> hello_world:module_info(). [{exports,[{multiply,2}, {add,2}, {helloWorld,0}, {callOthers,2}, {module_info,0}, {module_info,1}]}, {imports,[]}, {attributes,[{vsn,[311445890858620593432522823934882247552]}]}, {compile,[{options,[]}, {version,"4.9.2"}, {time,{2013,8,9,4,51,54}}, {source,"c:/Work/Erlang_code/hello_world.erl"}]}] |
Got a thought to share or found a
bug in the code?
We'd love to hear from you:
Name: | |
Email: | (Your email is not shared with anybody) |
Comment: |
Facebook comments: