Exadra37

Exadra37

It's possible to write a custom Guard to check for a blank string?

Sometimes I want to check if the input into a function is not a blank string.

My first approach:

defmodule Example do

  def do_stuff(string1, string2)
    when is_binary(string1)
    and byte_size(string1) > 0
    and is_binary(string2)
    and byte_size(string2) > 0 do

    # Do some stuff with string1 and string2, because now we know they cannot be:
    #  * ""
    #  * " "
    #  * "       "
  end
end

The problem here is that when a string contains spaces(":space: ", “:space: :another_space:”, etc.) the guard clauses above will not detect it and I reach the body of the function, but what I want is to detect the blank string in the guard clause.

So I tried to make a custom guard:

defmodule BlankGuard do

  defmacro is_not_blank?(string) do

    callback = fn
                <<" " :: binary, rest :: binary>>, func -> func.(rest, func)
                _string = "", _func -> true
                _string, _func -> false
              end

    is_blank = fn string, cb ->
                cb.(string, cb)
               end

    quote do
      unquote(string) |> is_binary()
      and unquote(string) |> byte_size > 0
      and unquote(string) |> is_blank.(callback)
    end
  end

end

And tried to use like this:

defmodule ExampleGuard do

  import BlankGuard

  def do_stuff(string1, string2) when is_not_blank?(string1) and is_not_blank?(string2) do

    # Do some stuff with string1 and string2, because now we know they cannot be:
    #  * ""
    #  * " "
    #  * "       "
  end
end

And I get the error:

== Compilation error in file lib/play.ex ==
** (CompileError) lib/play.ex:81: invalid expression in guard, anonymous call is not allowed in guards. To learn more about guards, visit: https://hexdocs.pm/elixir/guards.html

Following the link in the error it seems that custom guards can only invoke other guards.

So my question is if I am missing something or if this is not really possible to implement in a guard clause?

I know I can implement this in each module I want to check for a blank string, but looks like unnecessary code repetition:

# @link https://rocket-science.ru/hacking/2017/03/28/is-empty-guard-for-binaries
def empty?(<<" " :: binary, rest :: binary>>), do: empty?(rest)
def empty?(string = ""), do: true
def empty?(_string), do: false

Marked As Solved

kip

kip

ex_cldr Core Team

Guard functions are limited to this list. What they have in common is that they execute in constant time. Since binaries (Strings) as well as some other structures, are variable in size, there are no guard functions that operate on the structure as a whole except for length/1 which seems to be a bit of an exception to the constant time expectation.

Therefore I don’t think you’ll find a way to perform the checks you want as a guard.

Typically I would normalise input at an outer boundary layer. Like calling String.trim/2 in a changes that processes user input and therefore my guard would only have to check for "" which is possible,

Lastly, I would just note that the nature of empty? is open to a lot of interpretation and variability in the Unicode world given the wide range of code points that can be interpreted as whitespace.

Also Liked

kip

kip

ex_cldr Core Team

Thanks for the comment! Unicode simple regex’s coming up soon, and then the full Uncocde transform spec. Not quite so soon :slight_smile:

Even given the situation you describe I would tend to still enforce a boundary condition separately from processing. For example:

defmodule UtilsFor.Hash.Sha256 do
  alias UtilsFor.Text.Empty

  def salted_base64_encode(content, salt) when is_binary(content) and is_binary(salt) do
    do_salted_base64_encode(String.trim(content), String.trim(salt))
  end
  
  def do_salted_base64_encode("", _), do: {:error, :invalid_content}
  def do_salted_base64_encode(__, ""), do: {:error, :invalid_content}
  
  def do_salted_base64_encode(content, salt) do
    :sha256
    |> :crypto.hash(content <> salt)
    |> Base.encode64()
    |> wrap(:ok)
  end
  
  def wrap(term, wrap) do
    {atom, term}
  end
end

Just my 2.354c worth :slight_smile:

NobbZ

NobbZ

Long story short, you can’t check for blank strings in a guard, as you had to iterate over the string to do so, and that’s not possible.

cenotaph

cenotaph

Late to the discussion, just facing the same issues and wanted to update with the documentation. Maybe things have changed since the posting of this!

Such a guard would look like this:

def my_function(number) when is_integer(number) and rem(number, 2) == 0 do
  # do stuff
end

It would be repetitive to write every time we need this check. Instead you can use defguard/1 and defguardp/1 to create guard macros. Here’s an example how:

defmodule MyInteger do
  defguard is_even(term) when is_integer(term) and rem(term, 2) == 0
end

and then:

import MyInteger, only: [is_even: 1]

def my_function(number) when is_even(number) do
  # do stuff
end

While it’s possible to create custom guards with macros, it’s recommended to define them using defguard/1 and defguardp/1 which perform additional compile-time checks.

Where Next?

Popular in Questions Top

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

Other popular topics Top

WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39523 209
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36432 110
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New

We're in Beta

About us Mission Statement