Modules
Module Declaration
-module(Name).
It's time to code already! Our first module will be very simple and useless. Open your text editor and type in the following, then save it under useless.erl:
声明模块(modules),所有的erlang的代码都是需要写在modules中的。
-module(useless).
export声明一个模块可以在外部被调用的函数,他可以是一个带有参数个数的函数定义的列表,中间用逗号隔开。
同一个模块中的函数可以使用同一个名称,但是参数个数不能相同。
-export([Function1/Arity, Function2/Arity, ..., FunctionN/Arity]).
-export([add/2]).
下面开始写第一个定义的函数了。
add(A,B) ->
A + B.
在erlang里是不使用 “return”的关键字的。最后执行的逻辑表达式的只会自动返回给调用者。
定义一个hello的函数
%% Shows greetings.
%% io:format/1 is the standard function used to output text.
hello() ->
io:format("Hello, world!~n").
注意,上面用到了一个函数 io:format/1 这个应该是定义在io的模块中的,所以我们在文件的首部应该导入这个模块,语法为:
-import (io, [format/1]).
最后一个函数
greet_and_add_two(X) ->
hello(),
add(X,2).
最后我们的文件应该是这样的。
-module (test).
-export ([add/2,hello/0,greet_and_add_two/1]).
-import (io, [format/1]).
%% add function, add two number.
add(X,Y) ->
X + Y .
%% Shows greetings.
%% io:format/1 is the standard function used to output text.
hello() ->
io:format("Hello, world!~n").
%% greet with you and add two number.
greet_and_add_two(X) ->
hello(),
add(X,2).
下面我们开始编译代码吧。
转载于:https://blog.51cto.com/gairuyi/1088760