Binary patterns - why can’t I use << <<1,2,3>>/bitstring >> as a pattern as I can use it to build a binary?

Why can’t I use << <<1,2,3>>/bitstring >> as a pattern as I can use it to build a binary?

13> << <<1,2,3>>/binary >>. <<1,2,3>> 14> << <<1,2,3>>/binary >> = <<1,2,3>>. * 1:4: illegal pattern

Using bitstring doesn’t help.The logic is otherwise that what you use to construct a term you can also use as a pattern.


The documentation states that nested binary patterns are not allowed in a match, it does not say why though. You can of course bind the result to a var and use that in the match.

I was interested, what terrible things might happen if I remove the guard that prevents this here ?

Yet, nothing bad happened :slight_smile: , seemingly… I did not check for non-obvious bad things (memory leaks etc), but it does open the door for deep recursion perhaps. There is surely a solid reason why this is not allowed, none the less.

Would love to ping Bjorn, but on vacation I believe.


Supporting this example would be unproblematic, but if that is allowed one would expect other nested patterns to also be allowed. For example:

<< <<X/bitstring>>/bitstring, "xyz", Y/bitstring>>

Now that is more problematic.

When matching the binary <<"xyzxyz">>, what values should the X and Y variables be bound to? Should X be bound to <<>> or to <<"xyz">>?

When the exact semantics have been determined, it needs to be implemented in an efficient way, which is not exactly a trivial task.

That’s why we don’t allow any nested binary patterns.

Yes, I am on vacation, but I happened to see this anyway. I have an iPad but no computer at the moment.

In general when removing language restrictions from the erl_lint module, I expect that the compiler will crash. That it doesn’t in this case is probably because the nested pattern is a literal value that is handled by the same code that handles other literal values such as integers. However, I expect that the BEAM code produced would be worse than for the pattern <<1,2,3>>.


I definitely understand and agree that such a pattern should not be allowed as it involves a “search” which pattern matching does not allow/support.

OK, so no nested binary patterns. I will have to survive that. :wink: :smile: