Today I Learned

Pattern Match Using The Concatenating Operator <>

While reading Learn Functional Programming with Elixir, I picked up a nice little tidbit for using Elixir’s <> operator with pattern matching. In Elixir, we can use <> to concatenate two strings.

iex> "Hello " <> "World!"
"Hello World!"

Thanks to the power of pattern matching, we can also use it to pattern match the beginning of a string.

iex> "Hello " <> world = "Hello World!"
iex> world

However, we cannot use it to pattern match when the variable is on the left side of the <> operator.

iex> hello <> " World!" = "Hello World!"
** (CompileError) a binary field without size is only allowed at the end of a binary pattern and never allowed in binary generators

While we could get fancy and use something like String.reverse to flip our string and pattern match that way, as suggested in the book, we are probably better off just using Regex.