distinct elements in a list



On 6/17/07, sen1 at math.msu.edu <sen1 at math.msu.edu> wrote:
>
> Hello,
>   Given a list 'list_1', one way to make a list of the distinct
>   elements of 'list_1' is;
>
> listify(setify(list_1))$
>
> Is there a better (i.e., faster) way ?
>

This is a good and fast way.  Setify uses sorting (using orderlessp as the
order) to put equivalent elements next to each other. You could also use
hasharrays, something like this:

unique_elements(l) :=
    if l=[] then []
    else ( kill(unique_elements_hash),
           for i in l do unique_elements_hash[i]:i,
           listarray(unique_elements_hash))$

Setify does not use the hash technique because it wants the elements in
standard order. (Some quick experiments seem to show that listarray returns
the elements in standard order, too..., though.)

In principle, you'd expect the hasharray approach to be faster; I am not
sure what the practicalities look like.  If you perform some interesting
benchmarks (e.g. elements of l are all numbers; elements of l are complex
expressions; elements of l are very similar objects; sizeof(l) approx = to
sizeof(unique(l)); sizeof(l) >> sizeof(unique(l)) etc. etc.), let us know.

             -s