[erlang-questions] Sorting a list according to another list
Alexander Lamb
alexander.lamb@REDACTED
Wed Apr 23 12:06:35 CEST 2008
Thanks a lot, (you code is obviously much more efficient than mine:-)
My situation is clearly B from your examples.
So I tried your code. It works (except I changed the "==" with "=:="
under the assumption that "when not certain, use =:="
But now I tried to be smart and add a second test (I would like to
test key at position 1 and 2 in the tuples).
So here is what I did:
ps_sort_features2(Features,Template) ->
{Sorted, Tail} = lists:foldl(
fun(Feature, {L1, Rest}) ->
{L1 ++ [X || X <- Rest, element(1,X) =:= element(1,Feature) ,
element(2,X) =:= element(2,Feature)],
[X || X <- Rest, element(1,X) =/= element(1,Feature)
or element(2,X) =/= element(2,Feature)]}
end,
{[], Features},
Template),
Sorted ++ Tail.
Now this does not work.
It doens't like the "or" in the second list comprehension. What I was
trying to do is accumulate in L1 all element which match keypos 1 and
2 (using the comma) and accumulate in Rest all elements which don't
match either keypos1 or keypos2.
So, how do I express a "or" in a list comprehension?
Alex
Le 23 avr. 08 à 11:12, Ulf Wiger (TN/EAB) a écrit :
> Alexander Lamb skrev:
>> 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.
> [...]
>> Isn't this a very common situation?
>
> I've come across it every once in a while...
>
> I guess there are a few different scenarios:
>
> A The unsorted list must only contain keys that are
> in the reference list
> B Items not found in the reference list can be appended
> to the sorted list
> C The list to be sorted is "semi-sorted", in that the
> algorithm should preserve order as far as possible
> ...
>
> A fairly complex version of C can be found in
> systools_make:sort_appls/1 in OTP's SASL application.
> It tries to sort a list of applications, preserving
> the existing order as far as possible, while still
> preserving dependency restrictions.
>
> A version of B could be (not tested or compiled):
>
> sort(L, Keys, KeyPos) ->
> {Sorted, Tail} =
> lists:foldl(
> fun(K, {L1, Rest}) ->
> {L1 ++ [X || X <- Rest,
> element(KeyPos,X) == K],
> [X || X <- Rest,
> element(KeyPos,X) =/= K]}
> end, {[], L}, Keys),
> Sorted ++ Tail.
>
> AFAIK, lists:keytake/3 only exists in OTP R12B.
> lists:keydelete/3 only deletes the first occurrence
> of the key.
>
> BR,
> Ulf W
>
More information about the erlang-questions
mailing list