Finding unique elements of a list
Ulf Wiger (AL/EAB)
ulf.wiger@REDACTED
Wed Dec 1 18:10:23 CET 2004
To my knowledge, there's no such function.
Not that I doubt your ability to write one yourself,
but here's a suggestion:
u(L) -> u(L, []).
u([H|T], Acc) ->
case lists:member(H,Acc) of
true -> u(T, Acc);
false -> u(T, [H|Acc])
end;
u([], Acc) ->
lists:reverse(Acc).
Here's another one, shorter, O(1), and, most importantly,
cuter (functional purists may retch at will):
u2(L) ->
T = ets:new(temp,[set]),
L1 = lists:filter(fun(X) -> ets:insert_new(T, {X,1}) end, L),
ets:delete(T),
L1.
Works only on newer erlangs (newest R9C and R10, I believe).
/Uffe
> -----Original Message-----
> From: owner-erlang-questions@REDACTED
> [mailto:owner-erlang-questions@REDACTED]On Behalf Of James Hague
> Sent: den 1 december 2004 17:48
> To: 'erlang-questions@REDACTED'
> Subject: Finding unique elements of a list
>
>
> 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, 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. Is there an obvious library
> function I'm not seeing? Feels like there should be lists:unique/1.
>
More information about the erlang-questions
mailing list