lists:seq/3 strange behaviour

Pascal Chapier pascalchapier@REDACTED
Tue Jun 8 14:08:51 CEST 2010


In fact it does exactly what it is written in the documentation:


seq(From, To, Incr) -> Seq


Types:

        
>From = To = Incr = int()


        
Seq = [int()]


      

        


Returns a sequence of integers which starts with From
          and contains the successive results of adding Incr to
          the previous element, until To has 
been reached or
          passed (in the latter case, To is 
not an element of
          the sequence). Incr defaults to 1.

        

Failure: If To<From-Incr and Incr
          is positive, or if To>From-Incr 
and Incr is
          negative, or if Incr==0 and From/=To.

and implemented in the code:

seq(First, Last, Inc) 
    when is_integer(First), is_integer(Last), is_integer(Inc) -> 
    if
        Inc > 0, First - Inc =< Last;
        Inc < 0, First - Inc >= Last ->
            N = (Last - First + Inc) div Inc,
            seq_loop(N, Inc*(N-1)+First, Inc, []);
        Inc =:= 0, First =:= Last ->
            seq_loop(1, First, Inc, [])
    end.


But you are right, the purpose of the If test is to evaluate the length of the list, and as there is no default contition which could produce an empty list, I guess that the intent was to generate an exception when parameters cannot produce finite non empty list. So I think it is a bug and tha the code should be

seq(First, Last, Inc) 

    when is_integer(First), is_integer(Last), is_integer(Inc) -> 

    if

        Inc > 0, First + Inc =< Last;

        Inc < 0, First - Inc >= Last ->

            N = (Last - First + Inc) div Inc,

            seq_loop(N, Inc*(N-1)+First, Inc, []);

        Inc =:= 0, First =:= Last ->

            seq_loop(1, First, Inc, [])

    end.

and the doc: Failure: If To<From+Incr and Incr
          is positive, or if To>From-Incr 
and Incr is
          negative, or if Incr==0 and From/=To.

Or, a solution that I prefer, add a default condition which return an empty list as you suggest.

Pascal.



 		 	   		  
_________________________________________________________________
La boîte mail NOW Génération vous permet de réunir toutes vos boîtes mail dans Hotmail !
http://www.windowslive.fr/hotmail/nowgeneration/


More information about the erlang-questions mailing list