Most of the books or online resources I've seen are all using records to hold the state of a process (probably because that was the way for more(?) than a decade). On the other hand, maps are effectively used to replace tuples in stdlib (for example childspecs in the supervisor module).
As an example, I am working my way through Learn You Some Erlang's Finite State Machines chapter and the state
record could be replaced with a map, declared in the init/1
callback needed by gen_fsm
.
.hrl
files make it harder to track errors. Also, would it be more efficient?
I know that a well-thought out benchmark would answer my question but I am only a couple weeks into learning Erlang and the maps module is fairly new and still changing.
UPDATE: Thanks to I GIVE TERRIBLE ADVICE, I read the LYSE chapter on maps more thoroughly and the answer is clear:
Using records has the advantage that the keys are known at compile time that brings advantages of
- fast access to specific values (faster than what is possible dynamically)
- additional safety (crash early rather than corrupting state)
- easier type checking
These make records absolutely appropriate for a process' internal state, despite the occasional burden of writing a more verbose code_change function.
On the other hand, where Erlang users would use records to represent complex nested key/value data structures (oddly similar to objects in object-oriented languages) that would frequently cross module boundaries, maps will help a lot. Records were the wrong tool for that job.
A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. The key and value parts of the pair are called elements.
A process can terminate itself by calling one of the BIFs exit(Reason), erlang:error(Reason), erlang:error(Reason, Args), erlang:fault(Reason) or erlang:fault(Reason, Args). The process then terminates with reason Reason for exit/1 or {Reason,Stack} for the others.
I've added a chapter to the Learn You Some Erlang website about maps specifically: http://learnyousomeerlang.com/maps
The Mexican Standoff section specifically compares maps to records and dicts. Semantically speaking, maps are more similar to dicts than records, and my recommendation would really be to use records where records made sense (restricted set of keys with known types with O(1) access), and maps where you'd have used dicts (heterogenous, flexible sets of key/value pairs).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With