[erlang-questions] guard expression restriction

Jeff Schultz jws@REDACTED
Fri Dec 3 03:44:33 CET 2010


On Thu, Dec 02, 2010 at 10:37:55AM +0200, Kostis Sagonas wrote:
> Hmmm... In any case, the paper I mentioned in my previous mail contains an 
> example of more clear and succinct code when user-defined guards are 
> allowed.

I'm pretty sure I wouldn't write your Figure 7 that way in anything
other than short-lived code that I planned to throw away.*

Transcribed, it's more or less

    foo2(Set) when gb_sets:is_set(Set) ->
	handlegbset(Set);
    foo2(Set) when sets:is_set(Set) ->
	handleset(Set);
    foo2(_) ->
	error.

This puts my code at the mercy of data-representation changes in
either referenced module that I have no control over.  (In fact,
gb_sets:is_set is explicitly "Not Recommended" in its documentation.)

I'd be much more likely to write something like

    -record(agg, {kind=error, set=error}).

    % Code to generate various kinds of #agg and pack them correctly
    % into the record . . . .

    foo3(Agg) when Agg#agg.kind =:= gb_set ->
        handlegbset(Agg);
    foo3(Agg) when Agg#agg.kind =:= set ->
	handleset(Agg);
    foo3(_) ->
	error.

I can maintain this, and I'm safe from changes in someone else's
datastructures that might make one kind of collection look like
another.


    Jeff Schultz


-----------------------------------------------------
*Of course, it's often the code you were most certain
to throw away that lives the longest :-(


More information about the erlang-questions mailing list