typestar

Records in Erlang

A named tuple with compile-time field sugar and defaults.

%% A record is a named tuple with compile-time field sugar.
-record(line, {number, state = idle, pair}).

main(_) ->
    L = #line{number = 7, pair = "red-white"},
    io:format("Line ~p on ~s pair~n",
              [L#line.number, L#line.pair]),
    io:format("Default state: ~p~n", [L#line.state]),

    Ringing = L#line{state = ringing},
    io:format("Now: ~p~n", [Ringing#line.state]),

    #line{number = N} = Ringing,
    io:format("Matched number ~p~n", [N]).

How it works

  1. -record(line, {...}) declares fields, some with defaults.
  2. L#line.number reads; L#line{state = ringing} copies-updates.
  3. #line{number = N} = R matches fields out by name.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
425
Tokens
126
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 126 seconds.

Type this snippet

Step 2 of 4 in Data shapes, step 16 of 31 in Language basics.

← Previous Next →

Records in other languages