Exadra37
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
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted”
Version...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
kip
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/1which 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/2in 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.Exadra37
I was checking in this moment your unicode library. Nice work
Well this is really unfortunate and annoying, because sometimes this is not the case:
Sometimes I just have a function that can be called internally from other modules and I want to be sure that I don’t get the blank string
" ".It seems that I don’t have another alternative then keeping checking for the input in the body of the function
For my purposes I would be happy if I could get a guard clause to work for the common white space
kip
Thanks for the comment! Unicode simple regex’s coming up soon, and then the full Uncocde transform spec. Not quite so soon
Even given the situation you describe I would tend to still enforce a boundary condition separately from processing. For example:
Just my 2.354c worth
Exadra37
This is exactly the type of solution that I am tired of using all hover the place each time I need to check for a blank string.
It’s ok when you need to do it 1 time, not when you need to keep repeating it a across projects.
If you notice the name of the module is
UtilsForbecause is a package that I use across my projects, thus I would like to have the check for a blank string that I could use from a guard clause, not from the body of a function or with multiple functions heads.The
salted_base64_encodefunction is just one example where I need ot check for a blanks string, that happens to also be inside theUtilsForpackage. I just gave it to help illustrate why it’s needed.Anyway thanks for your insights
kip
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
newfunction 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
Exadra37
Your approach doesn’t do exactly what I want, aka a blank string
"lots of spaces here"will still go through, thus jeopardizing the hash, that could end-up to be generated from a blank content and salt.kip
Assuming I make
do_salted_base64_encode/2private (which I forgot to do), theString.trim/1calls 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.Exadra37
I did missed the call to
String.trim/1, and I also use it in myUtilsForpackage for the same effect. I think I should do a break, because I spent the entire day trying to figure out this issue, and I am starting to not seeing things clearlyThanks for all your insights.
dimitarvp
This can simply be injected with a macro module via something like
use EmptyStringGuard.Exadra37
To use in the guard itself?