Why can't I use a variable to the left of `<>` in a pattern match? Compiler or Theory?

spencer.christensen
Thu, 08 Feb 2024 20:15:25 +0000
Questions / Help

iex(26)> "hello " <> matched = "hello world"
"hello world"
iex(27)> matched
"world"
iex(28)> matched <> " world" = "hello world"
** (ArgumentError) the left argument of <> operator inside a match should always be a literal binary because its size can't be verified. Got: matched

I’m new to Elixir. I understand the basics of pattern matching. I am trying to understand conceptually why the above doesn’t work.

My understanding is that the evaluation of a pattern moves left → right. Therefore, when "hello " <> matched is evaluated the compiler is given a fixed starting place. Since it has a fixed location at the start, it can infer anything moving forward as it knows where it started.

The opposite, matched <> " world" = "hello world", fails. To my human brain this seems like a very simple match operation. However I understand that compilers and human brains have different skillsets and abilities.

I’m fine with this not working in Elixir. I don’t need it to. My main question is whether this a case where the compiler could theoretically be rewritten to have some sort of logic like “if pattern starts with variable, go right → left” or is there a deeper problem here where going “backwards” is a Hard Problem in computer science (CS)? I’m a self-taught dev so please forgive me is there is a rather obvious answer from a formal CS background.

Thanks!

9 posts - 6 participants