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

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.

2 Likes

Thanks for your contribution :slight_smile:

I am aware of it, that’s why I replied:

In my opinions this aren’t true custom guards, because of the limitations in the accepted answer :wink:

1 Like