Question

I have a tuple:

Data = {
    'F_01_heirId', ["ak238", "ak239", "ak240", "ak241" ...],
    'F_01_0014', ["some text", "some more text", "a some more", "xcuub", ...],
    'F_02_0010', ["azcde", "axvdss" "scssd", "abcdefg as" ...],
    'F_02_0014', ["1222", "1", "1", "10", ...],
    ...
    }

Need to sort Data tuple by F_02_0010, as we are sorting 'F_02_0010' according to the sorting change the respective elements of other lists too.

Here is the output that is required after sorting:

Data =  {
    'F_01_heirId', ["ak241", "ak239", "ak240", "ak238" ...]
    'F_01_0014', ["xcuub", "some more text", "a some more", "some text", ...],
    'F_02_0010', ["abcdefg as", "axvdss", "scssd", "azcde",  ...],
    'F_02_0014', ["10", "1", "1", "1222", ...],
    ...

    }
Was it helpful?

Solution

Your representation of Data is not very suitable for the task you want to do. Here are the steps you have to go through:

  1. Extract the column lists from Data and "zip" them into a list of rows lists (or tuples). You have to use a custom zip function that can handle more than 2 or 3 lists:

    manyzip([L|Ists]) ->
      Fold =
        fun(List, Acc) ->
          lists:zipwith(fun(A,B) -> [A|B] end,List,Acc)
        end,
      Reversed = lists:foldl(Fold, [[E] || E <- L], Ists),
      [lists:reverse(E) || E <- Reversed].
    
  2. Sort the rows on the respective element. You can use lists:sort/2 with a comparison function like fun(A,B) -> lists:nth(4, A) < lists:nth(4, B) end, where 4 is the index of F_02_0010 in the zipped lists.
  3. Convert the rows back to columns. manyzip/1 can be used as is for this task too!
  4. Restore their positions in the tuple.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top