[erlang-questions] Best way to test if empty dict/set/etc.?

Kostis Sagonas kostis@REDACTED
Fri May 31 09:25:48 CEST 2013


On 05/31/2013 09:03 AM, Vance Shipley wrote:
> On Thu, May 30, 2013 at 06:17:37PM -0400, Jonathan Leivent wrote:
> }  I noticed that a lot of the opaque data structures don't have an
> }  is_empty predicate.  What is the best way to test if one of these
> }  is empty?  Preferably an O(1) test, not size(X)==0 (unless that is
> }  O(1)), because the structure might be quite large.
>
> With gb_trees and gb_sets size/1 is O(1).  These opaque data structures
> happen to be tuples where the first element is the size:

I am afraid this statement (relying on the structure being a tuple) 
breaks the opacity of the data structure.  So does your call to 
element/2 below.

> I have in the past cheated by using clause heads which pattern match
> based on the size of the data structures (e.g.):
>
>       handle_call(Request, From, State) when element(1, State)>  ?MAX ->

So, this cannot possibly be the proper answer to Jonathan's question.

Since I've also stumbled across something analogous in the past, IMO the 
proper solution is to extend the API of these opaque data structures 
(these modules) by providing is_empty/1 functions for them.

I am sure the OTP folks would welcome a patch.

Kostis




More information about the erlang-questions mailing list