Sebb

Sebb

I have this helper function where I exploit the Errors in Guards feature.

def non_empty(val, _msg) when length(val) > 0, do: {:ok, val}
def non_empty(val, _msg) when map_size(val) > 0, do: {:ok, val}
def non_empty(val, _msg) when tuple_size(val) > 0, do: {:ok, val}
def non_empty(_val, msg), do: {:error, msg}

(I can call non_empty({:foo}, "") though length({:foo}) raises)

Is there a way to put this into a defguard - without using is_list/1 etc?

defguard enum_size... ???

Showing Posts 14 to 5

Sebb

Sebb OP

Sorry guys, I had a rough time and completely forgot about this thread.

Thanks for the insights.

As it seems we can’t exploit “errors in guards” inside a defguard, so I’ll go with your proposal.

kartheek

kartheek

@eksperimental :+1:

@dimitarvp I understand your point.

I am not criticising OP. I don’t know specifics of how non_empty function is being used.

I feel original non_empty function is little over engineered - covers list, map, tuple.

Most of the time, result tuple is pattern matched. Tuples are rarely iterated like list.

I use Enum.empty? Or for empty checks. I have some error_* which return error messages for a Boolean expression.

def error_if(true, msg), do: {:error, msg}
def error_if(_,_), do: :ok

ErrorUtils module has error_unless, error_if_nil, error_if_not_nil, etc.

Using these error funcs, with and case - I never felt need for anything else.

I wrote defguard for the first time today. This non_empty function does not need defguard as such.

dimitarvp

dimitarvp

Way too clever for my taste. I would not approve that in a PR and would prefer @eksperimental’s solution.

eksperimental

eksperimental

Wow, I am surprised by the result,
it could be that is_list(term) is faster than term == [], and so on with the other is_* functions. We could benchmark these.

The other thing is that it is so fast than the results are imprecise.
If the results are correct, then it pays off to always check for the type as I was doing.

kartheek

kartheek

This is simpler :+1: This will be slower than your original defguard.

As long as time complexity of expression is constant time O(1) - more or less same performance. Your versions are constant time too, so they will have similar performance.

In benchmark - your original defguard is performing the best :+1: .


Is better performance due to integer comparison vs equality operators?

eksperimental

eksperimental

@kartheek definitely yours is more performant.

Here’s another version I think even simpler, that builds on your idea.
defguard is_non_empty(term) when term not in [{}, [], %{}]

kartheek

kartheek

@eksperimental I feel both our solutions are very similar. Fun collaborating with you.

@Sebb I was running some benchmarking (just for fun) for below data. Your existing version was taking hit when data is non empty list. You may have to change it.
Which version to use ? you have to figure out by running benchmark or based on other requirements of in the project where it is used.

empty_list = []
list1 = Enum.to_list(1..3)
list2 = Enum.to_list(1..10)
list3 = Enum.to_list(1..100)
empty_map = %{}
map = %{1 => 2}
empty_tuple = {}
tuple = {1}

Benchee.run(%{
  "non_empty_empty_list"    => fn -> TestPattern.non_empty(empty_list, "") end,
  "non_empty_list1"    => fn -> TestPattern.non_empty(list1, "") end,
  "non_empty_list2"    => fn -> TestPattern.non_empty(list2, "") end,
  "non_empty_list3"    => fn -> TestPattern.non_empty(list3, "") end,
  "non_empty_empty_map"    => fn -> TestPattern.non_empty(empty_map, "") end,
  "non_empty_map"    => fn -> TestPattern.non_empty(map, "") end,
  "non_empty_empty_tuple"    => fn -> TestPattern.non_empty(empty_tuple, "") end,
  "non_empty_tuple"    => fn -> TestPattern.non_empty(tuple, "") end,
})
eksperimental

eksperimental

@kartheek, that is definitely the solution to the question by the OP

kartheek

kartheek

non_empty function using defguards:

defguard is_non_empty(enum) when ((enum == []) or (enum == {}) or (is_map(enum) and map_size(enum) == 0)) == false

def non_empty(val, _msg) when is_non_empty(val), do: {:ok, val}
def non_empty(_, msg), do: {:error, msg}

@eksperimental :+1: .

eksperimental

eksperimental

or you can make it a guard, it will not work for structs though.

  defguard is_non_empty(term)
           when (is_list(term) and term != []) or
                  (is_map(term) and map_size(term) > 0) or
                  (is_tuple(term) and tuple_size(term) > 0)

Where Next? Top

Trending in Questions Top

RSP87
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
kpanic
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
nseaSeb
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
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
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
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
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
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews