[erlang-questions] Dict size in guards
Richard O'Keefe
ok@REDACTED
Fri Feb 11 03:02:57 CET 2011
On 11/02/2011, at 5:05 AM, Alessandro Sivieri wrote:
> Hi all,
>
> is there a good reason for not allowing dict:size() in guards?
Yes. Who knows what dict:size() actually does?
Guards cannot and should not call functions.
> I mean, it
> looks exactly like length() for lists, in theory (of course, their
> implementations are different).
The inclusion of length/1 in guard tests has always been more than
a bit dodgy. It's better taste to avoid it. Not least because
if you do something like
f(L)
when length(L) > 10 -> long_case(L);
when length(L) > 5 -> medium_case(L);
when true -> short_case(L).
doesn't do what people often think. I've several times been
caught by that.
f(L) ->
N = length(L),
if N > 10 -> long_case(L)
; N > 5 -> medium_case(L)
; true -> short_case(L)
end.
is safer and only evaluates the length once.
A style warning "length/1 in guard" would be nice to have.
More information about the erlang-questions
mailing list