[erlang-questions] Dict size in guards

James Churchman jameschurchman@REDACTED
Fri Feb 11 18:10:02 CET 2011

  when length(L) > 10 -> long_case(L);
  when length(L) >  5 -> medium_case(L);
  when true           -> short_case(L).

(which is subtly wrong, as its misses the two following f(L)'s :-) )

can also be written like :


f(L,Len) when Len > 10 -> long_case(L);
f(L,Len) when Len >  5 -> medium_case(L);
f(L,_) -> short_case(L).

which i think i personally prefer....

and if the list L is only needed for length it gets even shorter (tho f/2 needs renaming if becoming f/1 )

also you could consider using an orddict, the api is identical to the dict, but it consists of a normal list so both of the above code works with out modification. There will obviously just be a lookup time difference for large lists (eg ones that are more than "4" :-) )


and if using normal dict, just replace length with dict:size() in the 2nd code

Also why does the compiler do a length check for every time you use length in a guard ?? I thought it did not do repetitive pattern matches that are "the same", so surly repetitive guard would also be similarly optimised?

also "hacks" like [_,_,_,_,_,_,_,_,_,_,_|_] look very clever, and i guess for very long lists have a speed benefit, but again could the compiler not realise that when you put "when Len > 10" it only needs to check that the list is longer than 10? not get the genuine numeric length and then numeric compare to 10. That seems a basic optimisation that could be made

also, why does is_list(tl(tl(tl(tl(tl(tl(L))))))) compile better?? it this true?? it looks really nasty!

On 11 Feb 2011, at 15:47, Alessandro Sivieri wrote:

> Well, I think guards are more elegant than case/if statements; but the
> Erlang limitation forces you to use the latter, that's all.
> I mean, it is not a problem to get the dictionary length as the first
> operation of a function and create an if statement, but...
> -- 
> Sivieri Alessandro
> alessandro.sivieri@REDACTED
> http://www.chimera-bellerofonte.eu/
> http://www.poul.org/

More information about the erlang-questions mailing list