[erlang-questions] Sorting a list according to another list

Alexander Lamb <>
Wed Apr 23 10:53:36 CEST 2008


Hello List,

I have a list of tuples:

[ {Type,Item,Value}, ... ]

that I would like to sort according to another list of tuples, using  
Type and Item as keys.

I didn't manage to use two keys so here is how I did it:

ps_sort_features(Features,Template) ->
	Find = fun(F,Acc) ->
		{_Type,Item,_Value} = F,
		case lists:keytake(Item,2,Features) of
			{value, Feature, _Remaining}     -> lists:append(Acc,[Feature]);
			false						-> Acc
		end
	end,
	lists:foldl(Find,[],Template).

Does this seem ok?

I basically take the Template (my reference list) and use a foldl  
function to Find occurences of Features from Template.
Features can be a subset of Template. Also, Value may be different so  
my resulting list has to be a reordered Features list.

In summary, I am reordering Features by following the order of Type  
and Item in Template.

Isn't this a very common situation?

Thanks,

Alex



More information about the erlang-questions mailing list