← Back to lesson 16: Describe a module and one record

Describe a module and one record: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Use module attributes, exports, records, and record patterns.

Compile a Book record and call a function that reads its page field.

Run this first

Run it once, change one input, and compare the new result.

Original full example
%% 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}) returns true.

Steps for the full example

  1. Read -record(book, {...}).: Declare record fields and defaults.
  2. Read #book{pages = Pages}: Match a book record and extract one field.
  3. Read -export([long/1]).: Make long/1 callable from other modules.

Original lesson notes

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.

Symbols and terms
-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.
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.

Original full exercise

Add an author field with the default unknown.

Exercise starter
-record(book, {title, pages = 0, ____ = ____}).

Declare author = unknown.

Show hint

Record defaults are ordinary Erlang terms.

Show original answer
Reference answer
-record(book, {title, pages = 0, author = unknown}).
Is a record a tagged map at runtime?

No. Records compile to tuples, so keep them behind module boundaries.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references