Nicholas Drake
Nicholas Drake

Reputation: 149

Why can't Erlang static data structures be changed?

My understanding of Erlang is you have

  1. all data structures are immutable
  2. some data structures are static e.g. records i.e. at compile time
  3. some data structures are dynamic e.g. maps i.e. at runtime

Given = that everything is copied including static data structures like maps

Question = why can't we change the record?

(Guess at) Answer = because the record is defined in the header macro which is changed by the pre-processor.

(Guess at) Incorrect answer = because the data structures has fixed memory size (it doesn't) and unlike C arrays it isn't in contiguous memory but rather a linked list?

Upvotes: 2

Views: 125

Answers (1)

legoscia
legoscia

Reputation: 41618

(Guess at) Answer = because the record is defined in the header macro which is changed by the pre-processor.

That's pretty close. Records are a compile time feature: a record is just a tuple with a special layout, and during compilation all record operations are converted into tuple operations.

So given this record definition:

-record(foo, {a, b = default_b}).

#foo{a = x} gets converted to {foo, x, default_b} by the compiler, and a record access such as MyRecord#foo.x becomes something like element(MyRecord, 2). (except that it also checks that MyRecord is a foo record, and raises a badrecord error otherwise)

That's why you can't change the number of elements of a record at runtime: any code that handles such records would need to be recompiled in order to access the right fields. This is similar to how C code needs to be recompiled if you change the layout of a struct.

Upvotes: 5

Related Questions