I am learning erlang and I stumbles over some behaviour I cannot quite understand. Take this piece of code. (I know there are existing libraries for what I am programming, but as I stated, I do this for educational purposes):
-module (codec).
-compile (export_all).
-record (node, {symbol, weight, order, left, right, parent} ).
-record (tree, {root, nodes} ).
highestOrderForWeight (Weight, Tree) ->
lists:max ( [Node#node.order || Node <- Tree#tree.nodes, Node#node.weight == Weight] ).
swapMaybe (Node, Tree) ->
case highestOrderForWeight (Node#node.weight, Tree) of
Node#node.order -> pass;
Node#node.parent -> pass;
Tree#tree.root -> pass;
Partner -> io:format ("Swapping ~p with ~p.~n", [Node#node.order, Partner] )
end.
The compiler is not at all amused about my code:
./so.erl:11: illegal pattern
./so.erl:12: illegal pattern
./so.erl:13: illegal pattern
error
It has appearently some trouble digesting records in patterns, because when I change my code to this clumsy work-around, it compiles fine:
swapMaybe2 (Node, Tree) ->
[Order, Parent, Root] = [Node#node.order, Node#node.parent, Tree#tree.root],
case highestOrderForWeight (Node#node.weight, Tree) of
Order -> pass;
Parent -> pass;
Root -> pass;
Partner -> io:format ("Swapping ~p with ~p.~n", [Node#node.order, Partner] )
end.
Questions:
- How do I access record fields in patterns?
- If it is not possible to do so, why is that so?
- If it is not possible to do so, what is the common practice to work around that?
Actually records are just a compile time syntactic sugar and you can look at the actual constructs by using
'E'compiler option. For exampleNode#node.orderwill be replaced by something like this:And of course when you try to use
Node#node.orderas a patter compiler reportsillegal patternfor this construct.Your
swapMaybefunction can be rewritten like this: