Finding unique elements of a list

Carsten Schultz <>
Wed Dec 1 18:29:56 CET 2004


Hi!

On Wed, Dec 01, 2004 at 10:47:38AM -0600, James Hague wrote:
> Is there a standard Erlang library function or idiom for removing duplicate
> items from an unsorted list?  Ideally the elements in the final list should
> be in the order they were passed in, except without duplicates:
> 
> 	[3,5,2,2,3] -> [3,5,2].
> 
> If order doesn't matter there are some easy options:
> 
> 1. lists:usort(L)
> 2. gb_sets:to_list(gb_sets:from_list(L))
> 
> If order does matter,

and you do not care for performance, then a quick solution would be

unique([]) ->
    [];
unique([H|T]) ->
    [H|unique(lists:filter(fun(X) -> X =/= H
			   end, T))].

But, yes, this is more reasonable in Haskell and stolen from its
library :-)

> then the only thing I've come up with is to build an ets table or
> gb_set iteratively, adding each element not previously in the table
> or set to a list of unique items.

Definitely the better option.

Sorry, that probably was not really helpful...

Greetings,

Carsten

-- 
Carsten Schultz (2:38, 33:47), FB Mathematik, FU Berlin
http://carsten.codimi.de/
PGP/GPG key on the pgp.net key servers, 
fingerprint on my home page.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20041201/3f6a04ce/attachment.bin>


More information about the erlang-questions mailing list