Pinning in binary match

Given the following:

iex(1)> "a" <> x = "ab"
iex(2)> x

The following should also work (according to

iex(3)> y = "a"
iex(4)> ^y <> x = "ab"
** (CompileError) iex:4: a binary field without size is only allowed at the end of a binary pattern

I’m expecting

y = "a"
^y <> x = "ab"

to be equivalent to

"a" <> x = "ab"

Am i missing something?

1 Like

Length of "ab" is 2 bytes right? What is the length of y? Since it’s variable it’s length is known only on the runtime, so you have to tell compiler how many bytes do you want to match.

Tnx! That makes sense.

Yep, by default binary matching matches like an integral, which is most assuredly not what you want, but it cannot do it based on a binary by default either because it has to know the length. :slight_smile:

EDIT: This could be added as a language feature. Internally pinning a variable in the <> style could call the binary length function to get the length, then do the internal matching based on both the binary, the length, and defining it as a binary. This would be a language enhancement, not backwards compatible (but who’s using it the way it currently is anyway?), and makes more sense. Someone could PR it to Elixir core? :slight_smile: