Chuyển đến nội dung

Bài 3 · Getting Started

Your First Module: Writing and Compiling

Write your first Erlang module, export functions, compile it with erlc or c/1, run it from the shell and understand attributes, arity and export rules.

The shell is great for experiments, but real programs live in modules. A module is a file that groups related functions. Its name is the file name without .erl, and the first line of the file must declare the same name. In this lesson you write a module, compile it and call it.

The smallest module

Create a file called hello.erl:

ERLANG
-module(hello).
-export([world/0, greet/1]).

world() ->
    io:format("Hello, world!~n").

greet(Name) ->
    io:format("Hello, ~s!~n", [Name]).

Let us walk through it line by line.

  • -module(hello). declares the module name. It must match the file name.
  • -export([world/0, greet/1]). lists the functions other modules may call, written as name/arity. A function that is not exported is private to the module.
  • world() -> ... . defines a function with no arguments. The -> separates the head from the body, and the final period ends the definition.
  • io:format/1 and io:format/2 print text. In the format string, ~s inserts a string and ~n is a newline.

Compiling and running

Open the shell in the same folder as the file and compile it:

ERLANG
1> c(hello).
{ok,hello}
2> hello:world().
Hello, world!
ok
3> hello:greet("Ada").
Hello, Ada!
ok

c(hello) compiles hello.erl into hello.beam and loads it. Both calls return ok after printing, because io:format returns ok, and the value of the last expression in a function is its return value. Functions in Erlang always return something.

You can compile from the command line too:

Terminal
erlc hello.erl
erl -noshell -s hello world -s init stop

erlc writes hello.beam next to the source. In the second command, -s hello world calls hello:world() and -s init stop ends the VM. Note that -s requires the function to exist with arity zero.

If you see undef, the module was not loaded, the function is not exported, or you used the wrong arity. hello:greet() fails with undef even though greet/1 exists, because arity 0 is a different function.

Several clauses, one function

A function may have several clauses separated by semicolons. Erlang tries them from top to bottom and uses the first one whose pattern fits.

ERLANG
-module(shapes).
-export([area/1]).

area({square, Side}) ->
    Side * Side;
area({rectangle, W, H}) ->
    W * H;
area({circle, R}) ->
    3.14159 * R * R.

The shell:

ERLANG
1> c(shapes).
{ok,shapes}
2> shapes:area({rectangle, 3, 4}).
12
3> shapes:area({circle, 2}).
12.56636

If no clause matches, you get a function_clause error. Pattern matching goes deeper into this.

Attributes and comments

Lines beginning with a hyphen are attributes. Besides -module and -export, you will often see:

ERLANG
-module(calc).
-export([double/1]).
-import(lists, [map/2]).      % call map/2 without the lists: prefix
-define(FACTOR, 2).           % a macro, used as ?FACTOR
-vsn("1.0").                  % your own version tag

double(List) ->
    map(fun(X) -> X * ?FACTOR end, List).

Comments start with % and run to the end of the line. By convention %% is used for comments on their own line.

Two cautions: -import is allowed but discouraged by most style guides, because a prefixed call like lists:map/2 shows at a glance where a function comes from. Macros are expanded before compilation, and ?MODULE is a predefined macro that expands to the current module name.

The order of things

The attributes -module and -export must appear before the function definitions that use them, and every function you export must be defined. If you export greet/2 but write only greet/1, the compiler reports an error: function greet/2 undefined.

The compiler also warns about unused variables and functions. Treat warnings seriously: an unused variable often means a typo.

ERLANG
f(X, Y) ->
    X + 1.

compiles with Warning: variable 'Y' is unused. Prefix a deliberately unused variable with an underscore (_Y) or use just _.

Reloading code

Erlang can replace code in a running system. Edit hello.erl, then in the same shell run c(hello). again. The new version is loaded, and existing calls through hello:greet/1 use it. The VM keeps up to two versions of a module; a third load kills processes still running the oldest. This is the root of hot code loading, which you will see used in OTP releases.

A stand-in for compile and call

The following JavaScript imitates how a module with exports behaves. It is not Erlang code and does not run Erlang.

JS Stand-in: module with exports and arity (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: clauses tried top to bottom (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What must the -module attribute match?

    A file hello.erl must start with -module(hello).
  2. 2. Why does hello:greet() fail with undef when only greet/1 is defined?

    A function is identified by name and arity, so greet/0 does not exist.
  3. 3. What does c(hello). do in the shell?

    c/1 compiles the source file to a .beam file and loads it into the running system.
  4. 4. How do you silence an unused-variable warning on purpose?

    A name such as _Y tells the compiler you do not intend to use it.

Summary

  • A module is a .erl file whose first attribute -module(name). matches the file name.
  • Only functions in -export([name/arity]) can be called from outside.
  • c(Module). in the shell, or erlc file.erl, compiles to a .beam file.
  • Clauses are separated by ;, and a definition ends with .; the first matching clause runs.
  • % starts a comment; _Var marks a variable as intentionally unused.

Next: Projects with rebar3

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.