Erlang basics · Lesson 16 (open contents)
Describe a module and one record
Use module attributes, exports, records, and record patterns.
Run this first
Run it once, change one input, and compare the new result.
%% Save in book.erl and compile it
-module(book).
-export([long/1]).
-record(book, {title, pages = 0}).
long(#book{pages = Pages}) -> Pages >= 300.- Inside the module,
long(#book{title = <<"River">>, pages = 320})returnstrue.
Read from the first line down
- Read
-record(book, {...}).: Declare record fields and defaults. - Read
#book{pages = Pages}: Match a book record and extract one field. - Read
-export([long/1]).: Makelong/1callable from other modules.
Symbols are not secret signs
-record(book, {...}).Declare record fields and defaults.
#book{pages = Pages}Match a book record and extract one field.
-export([long/1]).Make long/1 callable from other modules.
Match each name to its meaning
module attribute
Forms such as -module, -export, and -doc describe compiled code.
record
A record gives tuple positions field names at compile time; its runtime value is still a tuple.
include file
Shared record definitions commonly live in an .hrl file included at compile time.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
Forms such as -module, -export, and -doc describe compiled code.
A record gives tuple positions field names at compile time; its runtime value is still a tuple.
Close the answer and try
Add an author field with the default unknown.
-record(book, {title, pages = 0, ____ = ____}).Target result: Declare author = unknown.
Stuck? Read one hint
Record defaults are ordinary Erlang terms.
After you run it, see one answer
-record(book, {title, pages = 0, author = unknown}).Think about it: Is a record a tagged map at runtime?
No. Records compile to tuples, so keep them behind module boundaries.
Remember these three lines
- 1
Attributes describe compiled modules.
- 2
Records name tuple positions at compile time.
- 3
Do not expose record layout as a public cross-language contract.