user3401408
user3401408

Reputation:

Sort a list with all three elements of a list, Erlang

I have a list in random order with structure:

L = [[{type1, Str12},{type2, Str22}, {code, Number12}, X],
    [{type1, Str14},{type2, Str24}, {code, Number14}, X],
    [{type1, Str15},{type2, Str25}, {code, Number15}, X],
    [{type1, Str13},{type2, Str23}, {code, Number13}, X],
    [{type1, Str11},{type2, Str21}, {code, Number11}, X],
     ...]    

Where, StrX, NumberX are variables: I have to sort it, order by first position string, second position string and third numeric string respectively. And nothing to do with all other remaining elements of the List. eg. Let us say,

L1 = [{type1, "Hello"},{type2, "World"}, {code, "00009"}, "india", 24, ...],
L2 = [{type1, "Alarm"},{type2, "Started"}, {code, "00203"}, "Japan", -, ...],
...etc.

Basically L should be like this:

L = [[{type1, Str11},{type2, Str21}, {code, Number11}, X],
    [{type1, Str12},{type2, Str22}, {code, Number12}, X],
    [{type1, Str13},{type2, Str23}, {code, Number13}, X],
    [{type1, Str14},{type2, Str24}, {code, Number14}, X],
    [{type1, Str15},{type2, Str25}, {code, Number15}, X], ...].

Quite Complicated for me, However, I tried like this but didn't work.

SortedHeirList = lists:sort(fun(A, B) -> 
                    get_type1_val(A) =< get_type1_val(B),
                    get_type2_val(A) =< get_type2_val(B),
                    get_Code(A) =< get_code(B),
               end, L).

Upvotes: 2

Views: 75

Answers (1)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

Using just lists:sort/1 didn't work?

1> L1 = [{type1, "Hello"},{type2, "World"}, {code, "00009"}, "india", 24], L2 = [{type1, "Alarm"},{type2, "Started"}, {code, "00203"}, "Japan"].        
[{type1,"Alarm"},{type2,"Started"},{code,"00203"},"Japan"]
2> lists:sort([L1, L2]).
[[{type1,"Alarm"},{type2,"Started"},{code,"00203"},"Japan"],
 [{type1,"Hello"},{type2,"World"},{code,"00009"},"india",24]]

See 8.11 Term Comparisons for more dtails.

Upvotes: 1

Related Questions