Chapter 10. Storing Structured Data

Tuples and lists are powerful tools for creating complex data structures, but there are two key pieces missing from the story so far. First, tuples are relatively anonymous structures. Relying on a specific order and number of components in tuples can create major maintenance headaches. This also means that tuples don’t let you refer to contents by name: you always have to know their location. Second, despite Erlang’s general preference for avoiding side effects, storing and sharing data is a fundamental side effect needed for a wide variety of projects.

Four tools provide more support for structured data. Maps work well when you want to refer to possibly varied information through a single list of names. Records will help you create labeled orderly sets of information. Erlang term storage (ETS) will help you store and manipulate those sets, and the Mnesia database provides additional features for reliable distributed storage.

Mapping Your Data

Referring to data by its place in a list or tuple can tax programmer memory and code quickly, especially if data comes and goes. Erlang 17 (and later) addresses this common challenge with a new data structure, the map. Map processing is slightly slower than list or tuple processing, but is often easier to work with: you don’t have to remember as much.

Creating a map requires a different syntax presenting keys and values:

1> Planemos = #{ earth => 9.8, moon => 1.6, mars => 3.71 }.
#{earth => 9.8,mars ...

Get Introducing Erlang, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.