Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use is_bitstring or is_binary in Elixir Guard for String?

Tags:

elixir

Let's take this simple function:

  @spec laBionda(String.t()) :: String.t()
  def laBionda(name \\ "you") when is_bitstring(name) do
    "One for #{name}, one for me"
  end

I only want to define the function for String inputs.

Should I use is_bitstring or is_binary on the Guard? Are there any differences? Both seem to be fine in that case.

like image 825
Marvin Rabe Avatar asked Jan 12 '19 15:01

Marvin Rabe


People also ask

What is a guard in Elixir?

Guards are a way to augment pattern matching with more complex checks. They are allowed in a predefined set of constructs where pattern matching is allowed. Not all expressions are allowed in guard clauses, but only a handful of them.

Is bitstring Elixir?

A bitstring is a fundamental data type in Elixir, denoted with the <<>> syntax.

What is a Charlist?

A group of one or more characters enclosed by [ ] as part of Like operator's right string expression. This list contains single characters and/or character ranges which describe the characters in the list. A range of characters is indicated with a hyphen (-) between two characters.


1 Answers

You should use is_binary/1.

Strings in Elixir are represented as binaries. Elixir binaries are sequences of bytes, whereas bitstrings are sequences of bits. While all binaries are bitstrings, not all bitstrings are binaries.

is_bitstring/1 can return true for some bitstrings that cannot be represented as a binary, for example, the single bit:

iex(1)> is_binary(<<1::1>>)
false
iex(2)> is_bitstring(<<1::1>>)
true

You expect strings only. Bitstrings that are not binaries are never desired, so the more specific is_binary/1 is the better choice.

like image 116
Adam Millerchip Avatar answered Oct 18 '22 20:10

Adam Millerchip