Matching literals

This made me happy

    iex(1)> "abc" <> x = "abc123"
   "abc123"
   iex(2)> x
   "123"

This made me sad

   iex(3)> 'abc' <> x = 'abcdef'
   ** (CompileError) iex:3: invalid literal 'abc' in <<>>
      (elixir) src/elixir_bitstring.erl:19: :elixir_bitstring.expand/6
      (elixir) src/elixir_bitstring.erl:9: :elixir_bitstring.expand/4
      (elixir) expanding macro: Kernel.<>/2
      iex:3: (file)

Since ‘xxx’ is just an Erlang list under the covers and pattern matching in Erlang
uses the “Literal” ++ Var a lot it would be very nice if ‘const’ ++ var was a legal
pattern in Elixir (this actually translates to very efficient code in the erlang VM :slight_smile:

4 Likes

I believe it does work:

iex(1)> 'abc' ++ x = 'abcdef'
'abcdef'
iex(2)> x
'def'
3 Likes

It actually is, but in your example you tried 'const' <> var.

<> is for binaries only, and "const" <> var is equivalent to erlangs <<"const", Var/binary>>.

5 Likes

Brilliant now I’m very happy :slight_smile:

5 Likes