Reputation: 81
I am finding it difficult to decipher this code. I could understand that there is an instance of a data structure; is it a record or map?
The query is regarding the last two line of the code does it update the record with Response
or does it check message_code
?
Response =
#{header =>
#{message_code => 'CONN_ESTABLISH_REQUEST',
protocol_instance => ?MGMT_PROTOCOL_IDENTIFIER,
transaction_identifier => 1},
content => #{revision_list => [0]}
},
#{header := #{message_code := 'CONN_ESTABLISH_CONFIRM'},
content := Confirmation} = Response
Upvotes: 3
Views: 87
Reputation: 41528
It's a map, not a record. (If it were a record, the record name would be between the #
and the {
.)
The last two lines perform a pattern match on the variable Response
. The code asserts that Response
is a map containing at least two keys, header
and content
. The value for header
must be a map containing at least one key, message_code
, whose value is 'CONN_ESTABLISH_CONFIRM'
. The value for content
will be stored in the variable Confirmation
.
If the value of Response
doesn't conform to all those requirements, this code will signal a badmatch
error.
Note that the behaviour is different depending on whether the right hand side of :=
contains:
If it is an unbound variable, the value for that key is simply stored in that variable. If it is a bound variable, the value for that key must match the value of that variable, otherwise you get a badmatch
error just like for a non-matching constant.
As you see, there are two different delimiters used, =>
and :=
. When constructing a new map (such as the first expression in your example), you can only use =>
, and when pattern matching, you can only use :=
. The idea is that they do different things: =>
stores a key-value pair in the map, while :=
extracts an existing key-value pair.
There is another case: updating an existing map. In that case you can use both. =>
can be used to add a new key to the map, while :=
can only be used to update an existing key, otherwise it signals a badarg
error. For example, if you wanted to add a "footer" to Response
, you have to use =>
:
NewResponse = Response#{footer => [some,data]},
%% this signals a badarg error:
NewResponse = Response#{footer := [some,data]},
while if you want to change the content
, you can use either:
NewResponse = Response#{content := 42},
NewResponse = Response#{content => 42},
Upvotes: 2