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.
%% 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
- 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.
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/1callable from other modules. - module attribute
- Forms such as
-module,-export, and-docdescribe 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
.hrlfile included at compile time.
Original full exercise
Add an author field with the default unknown.
-record(book, {title, pages = 0, ____ = ____}).Declare author = unknown.
Show hint
Record defaults are ordinary Erlang terms.
Show original 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
- Attributes describe compiled modules.
- Records name tuple positions at compile time.
- Do not expose record layout as a public cross-language contract.