Pattern matching on Bitstrings

Deankinyua

Deankinyua

6 hours ago

Assume that you have a long string of text that you want to display to the user. You want to display a maximum of 60 characters and add an ellipsis if and only if the text was longer than 60 characters.

One approach would be to count the number of characters in the input string and if it is greater than 60 characters, use something like String.slice/3 to trim :

String.slice(input_string, 0..59)

That approach works perfectly well only that it is less performant because you need to make extra function calls just to count the number of characters. What if you could just pattern match on the string and get exactly the size of characters that you want?? As a matter of fact, you can … using bitstrings!!

A string in Elixir is represented as a binary. Somewhere in this documentation you are going to read this :

#A string is a UTF-8 encoded binary
is_binary("hello")
>> true

Binaries on the other hand are bitstrings where the number of bits is divisible by 8.

“Bit” + “strings” - A sequence of bits (nothing complicated).

If what we said above is true, then a bitstring:

  • with 64 bits is a binary
  • with 8 bits is a binary
  • with 16 bits is a binary
  • with 49 bits is not a binary (not divisible by 8)

Now that we have all the background knowledge, we can proceed to understand how we present all this stuff.

A bitstring is denoted with the <<>> syntax.