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

Vance Shipley vances@REDACTED
Fri May 31 09:03:48 CEST 2013

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:

     1> G1 = gb_trees:empty().  
     2> G2 = gb_trees:insert(foo, 1, G1).
     3> G3 = gb_trees:insert(bar, 2, G2).
     4> gb_sets:from_list([1,2,3,4,5]).

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 ->


More information about the erlang-questions mailing list