Stan
Stan

Reputation: 3

Erlang - Removing repeating tuples according to first value

I am trying to create a function that will look into a list of tuples and remove the ones that have identical first elements. For example:

rmvSameTpl([{2,1}, {2,1}, {3,1}, {2,1}]).

should return [{2,1}, {3,1}].

The problem is my function always returns only the first tuple and as I'm a beginner I can't figure out why that is the case?

-export([rmvSameTpl/1]).

rmvSameTpl ([])-> [];
rmvSameTpl ([Z])-> [Z];
rmvSameTpl ( [H|T] ) -> 
    [H| [L || L<-rmvSameTpl(T), (element(1, H)) /= (element(1, T))] ].

Any help will be appreciated.

Upvotes: 0

Views: 554

Answers (3)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

Your approach has O(N^2) time complexity. There is obvious simple O(N*logN) solution:

1> lists:ukeysort(1, [{2,1}, {2,1}, {3,1}, {2,1}]).
[{2,1},{3,1}]

Upvotes: 4

Pascal
Pascal

Reputation: 14042

you just made a typo, you use element(1,T) instead of element (1,L). using

[H| [L || L<-rmvSameTpl(T), (element(1, H)) /= (element(1, L))] ].

your code works, but I am not comfortable with performance and stack size if you ever use big lists.

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170723

You are doing a wrong comparison in the last case: (element(1, H)) /= (element(1, T)) instead of (element(1, H)) /= (element(1, L)). It fails with an exception, since T is a list and not a tuple. But in Erlang list comprehensions, failing filters are treated as false, so [L || L<-rmvSameTpl(T), (element(1, H)) /= (element(1, T))] ends up being the empty list.

Upvotes: 0

Related Questions