exported variables (was: RE: How to make GS Widgets)

Jay Nelson <>
Fri Apr 16 17:55:47 CEST 2004


Cedric wrote:
 >> {Red,Green,Blue} = case SuppliedColor of
 >>                                       {TestRed,TestGreen,TestBlue} when
 >>                                             is_integer(TestRed),
 >>                                             is_integer(TestGreen),
 >>                                             is_integer(TestBlue),
 >>                                             TestRed =< 255, TestRed => 0,
 >>                                             TestGreen =< 255, TestGreen 
=> 0,
 >>                                             TestBlue =< 255, TestBlue 
=> 0, ->
 >>                                               SuppliedColor;
 >>                                        _ ->
 >>                                               {0,0,0}
 >>                               end
 >>

Tony replied:
 > The above test is ok (except that you write >= not => in Erlang)
 > An other version I like is to check all at once :-)
 > the band/bor/bnot are bitwise operators.
 >
 > case SuppliedColor of
 >    {R,G,B} when (R bor G bor B) band (bnot 255) == 0 ->
 >           SuppliedColor;
 >     _ ->
 >           {0,0,0}
 >  end.

I tend more towards Joe's inefficient clarity style.  Make a support
function so that you don't have this kind of complicated indentation:

validate_colors({R, _, _}) when not is_integer(R); R < 0; R > 255 ->
   {0,0,0};
validate_colors({_, G, _}) when not is_integer(G); G < 0; G > 255 ->
   {0,0,0};
validate_colors({_, _, B}) when not is_integer(B); B < 0; B > 255 ->
   {0,0,0};
validate_colors({R, G, B}) ->
   {R, G, B};
validate_colors(_) ->
   {0,0,0}.

Then in the code, call this:

{Red, Green, Blue} = validate_colors(SuppliedColor)

For me it is easier to test and to visually verify correctness, and easy
to modify if the rules change.  Whenever you find yourself doing
complicated pattern matching with when clauses, case statements or
an if, consider using a support function and let the language do the
pattern matching in the function headers.

jay




More information about the erlang-questions mailing list