[erlang-questions] Nested Record Pattern Matching in R14A

Robert Virding rvirding@REDACTED
Tue Jul 20 02:41:44 CEST 2010


I just want to expand a little on what Tuncer has written.

No, it is not a bug, it is most definitely intended.

The basic principle is that the syntax used to match and pull apart a
term is the same as that used to construct it. So you both construct
and match a list using syntax like [A,B|C] and for a tuple syntax like
{A,B,C}. For binaries the same principle applies though with them you
have more options. In all cases it is very explicit. This is both a
blessing and a curse with pattern matching.

While records in one sense are more abstract than lists or tuples the
same principle applies here as well, you use the same syntax to match
a record as to construct it. This is why the case that worked looked
like it does. What you were trying to do was use the syntax for
accessing fields in the records, it resembles trying to match a tuple
by writing a head like:

function_call(element(3) = State) -> ... ;

I hope this helps some,

Robert


On 17/07/2010, Tuncer Ayaz <tuncer.ayaz@REDACTED> wrote:
> On Thu, Jul 8, 2010 at 3:34 PM, Brian Williams wrote:
>> I converted a small search algorithm project to use the new nested
>> record syntax in R14A.
>> My records are:
>> -record(state, {yard_state}).
>> -record(solution_state, {state = #state{}, moves, depth}).
>> -record(astar_solution_state, {solution_state = #solution_state{},
>> fvalue}).
>>
>> I was able to use a line like this to access a field in the nested record:
>> Astar_Solution_State#astar_solution_state.solution_state#solution_state.state
>>
>> Based on the example in the reference manual, I thought the pattern
>> for matching the state field would be:
>>
>> function_call(#astar_solution_state.solution_state#solution_state{state
>> = State})
>
> Hi Brian,
>
> this is invalid and it's not how records are matched.
>
> It almost looks like an expression to update a record field:
> foo(Astar) when is_record(Astar, astar_solution_state) ->
>   State = #state{yard_state=foo_yard},
>   Astar#astar_solution_state.solution_state#solution_state{state=State}.
>
>> However, that gave me "illegal pattern" errors, and after a bit of
>> fiddling, I got this to work:
>> #astar_solution_state{solution_state = #solution_state{state = State}}
>>
>> Is this intended? Or a bug?
>
> It is intended.
>
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
>
>


More information about the erlang-questions mailing list