whysoserious
whysoserious

Reputation: 728

Concatenating Bitstrings in Elixir

This piece of code throws error:

 iex(35)> a = <<18::size(7)>>
     <<18::size(7)>>
 iex(36)> b = <<100::size(7)>>
     <<100::size(7)>>
 iex(37)> <<a <> b>>
     ** (ArgumentError) argument error

Why this code fails?

How can I concatenate bitstrings using variables?

(I updated to example according to mudasobwa's remarks)

Upvotes: 3

Views: 3279

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

How can I concatenate bitstrings using variables?

If you have binaries, use Kernel.<>/2:

iex|1 ▶ a = <<1, 2>>
#⇒ <<1, 2>>
iex|2 ▶ b = <<3, 4>>
#⇒ <<3, 4>>
iex|3 ▶ a <> b
#⇒ <<1, 2, 3, 4>>

It also works inside Kernel.SpecialForms.<<>>/1:

iex|4 ▶ << a <> <<3, 4>> >>
#⇒ <<1, 2, 3, 4>>

Alternatively you might explicitly tell the compiler you use binary:

iex|5 ▶ << a :: binary, <<3, 4>> >>   
#⇒ <<1, 2, 3, 4>>

If you have bitstrings, the latter option works: use an explicit type hint:

iex|6 ▶ a = <<18::size(7)>>
iex|7 ▶ << a :: bitstring, <<100::size(7)>> >>
#⇒ <<37, 36::size(6)>>

Upvotes: 10

whysoserious
whysoserious

Reputation: 728

The correct answer is to use a bitstring type hint:

iex(35)> a = <<18::size(7)>>
         <<18::size(7)>>
iex(36)> b = <<100::size(7)>>
         <<100::size(7)>>
iex(37)> <<a <> b>>
         ** (ArgumentError) argument error
iex(37)> <<a,  b>>
         ** (ArgumentError) argument error
iex(37)> <<a::bitstring,  b::bitstring>>
         <<37, 36::size(6)>>

Upvotes: 3

Related Questions