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!

https://hexdocs.pm/elixir/1.10.3/patterns-and-guards.html#custom-patterns-and-guards-expressions

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.

kip

kip

ex_cldr Core Team

I hear you, boilerplate gets to be a pain, no disagreement there. In most cases I’ve converged on using structs a lot more where a new function does validation and afterwards I trust that the struct has data of the right form and I never check it again. Another approach to creating a boundary between data validation/casting and operations on data.

This has dramatically reduced the amount of boilerplate - but not necessarily for the kind of function you describe above. Over and out :slight_smile:

kip

kip

ex_cldr Core Team

Assuming I make do_salted_base64_encode/2 private (which I forgot to do), the String.trim/1 calls on the 5th line will strip all leading and trailing whitespace resulting in "" for a string that is only whitespace before the call to the private function and therefore I think it does what you are after.

Where Next?

Popular in Questions Top

stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
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
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New

We're in Beta

About us Mission Statement