Reputation: 29896
How does one sort a list in Erlang depending on a tag for each element?
If I have a process which loops and receives a single value from multiple processes and then I want to arrange the list according to the tag(which is an index) as an element is received.
How does one do this without using BIFs?
I currently do the following but would like to arrange the list when an element is added, like an insertion sort using the tags.
fibLoop(calcData) ->
receive
{Number, Tag} ->
fibLoop([{Number, Tag}|calcData]);
Upvotes: 2
Views: 2307
Reputation: 1979
There are multiple ways to do what you want, a bit depending on what you want to use the value for later.
Easy solution would be to use gb_trees. gb_trees are a sorted structure that you can loop over using an iterator.
Or if you want to keep it simple and have a list you could use orddict (or possibly ordsets).
orddict:store(Number, Tag, CalcData)
to insert {Number, Tag} into an ordered list. See documentation for orddict for more information.
To get the smallest value in the list you can use hd/1, and to get the biggest lists:last/1 (not that I recommend lists:last, mind you).
Upvotes: 2
Reputation: 5327
Something like this would probably work:
insert({_, Tag} = Data, [{_,HTag}|_] = List) when Tag >= HTag ->
[Data | List];
insert(Data, [H | T]) ->
[H | insert(Data, T)];
insert(Data, []) ->
[Data].
Upvotes: 2