Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: choosing unique items from a list, using recursion

Given any list in Erlang, e.g.:

L = [foo, bar, foo, buzz, foo].

How can I only show the unique items of that list, using a recursive function? I do not want to use an built-in function, like one of the lists functions (if it exists).

In my example, where I want to get to would be a new list, such as

SL = [bar, buzz].

My guess is that I would first sort the list, using a quick sort function, before applying a filter?

Any suggestions would be helpful. The example is a variation of an exercise in chapter 3 of Cesarini's & Thompson's excellent "Erlang Programming" book.

like image 365
Alexander Von Kimmelmann Avatar asked Mar 13 '13 17:03

Alexander Von Kimmelmann


1 Answers

I propose this one:

unique(L) ->
    unique([],L).
unique(R,[]) -> R; 
unique(R,[H|T]) ->
    case member_remove(H,T,[],true) of
        {false,Nt} -> unique(R,Nt);
        {true,Nt} -> unique([H|R],Nt)
    end.

member_remove(_,[],Res,Bool) -> {Bool,Res};
member_remove(H,[H|T],Res,_) -> member_remove(H,T,Res,false);
member_remove(H,[V|T],Res,Bool) -> member_remove(H,T,[V|Res],Bool).

The member_remove function returns in one pass the remaining tail without all occurrences of the element being checked for duplicate and the test result.

like image 122
Pascal Avatar answered Sep 20 '22 00:09

Pascal