/ erlang

Erlang Data Structures : Records

  • Similar to struct in c.
  • Records have fixed number of elements.
  • Each field have a name.
  • It uses tuples under the hood.

Define Record

Lets take the tuple from previous post on tuples and convert that into a record.

{laptop,"Dell","Inspiron","i7","16GB"}.

We use -record(name,{Field1,[=Default]...}) module attribute to define a record.

-record(laptop,{brand,
                  model,
                  cpu="Intel",
                  ram
                 }).

If a records needs to be used in multiple modules, define it in a .hrl file, more like a header file in C.

To use the record defined in a .hrl file we use -include module attribute.

-include("laptop.hrl").

Create Record

Here we create a record from the above definition in function create() .

laptop.erl

create()->
    #laptop{brand="Dell", ram="16gb", model="Inspiron"}.

Syntax:
#RecordName{Field=Value...}

When we call laptop:create(). from the Erlang shell what we see is {laptop,"Dell","Inspiron","Intel","16gb"} that is because we must explicitly load the record details into shell using rr(laptop). .

#laptop{brand = "Dell",model = "Inspiron",cpu = "Intel",ram = "16gb"}
  • Fields can be specified in any order.
  • If we don't specify value for a field, either the default value will be assigned or it will be undefined.

Access Record Fields

We access values of individual fields in a record using . operator.

Syntax:
Variable#RecordName.FieldName.

15> L=laptop:test().
#laptop{brand = "Dell",model = "Inspiron",cpu = "Intel",ram = "16gb"}
16> L#laptop.brand.
"Dell"
17> 

Update Record

Syntax:
Variable#RecordName{FieldName=Value}.

17> L#laptop{ram="32gb"}.
#laptop{brand = "Dell",model = "Inspiron",cpu = "Intel",ram = "32gb"}

References:

Erlang Doc