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.
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.
A bitstring is a fundamental data type in Elixir, denoted with the <<>> syntax.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With