Haskell reordering list by value

I was wondering if there is an efficient / easy way to reorder the list of a list by matching the values ​​of another list that sets the order. More specifically, if I had the following list:

[["a", "1", "2"], ["b", "2", "3"]]

I would like to order it with the following list:

["b", "a"]

which leads to an ordered list:

[["b", "2", "3"], ["a", "1", "2"]]

Does anyone know how to do this?

Thanks in advance!

Best regards, Skyfe.

+4
source share
1 answer

It basically works by providing a special ordering function,

import Data.List
import Data.Ord
byLoc :: Eq a => [a] -> -- The list that we're sorting by
                 [a] -> -- First list
                 [a] -> -- Second list
                 Ordering
byLoc ords = comparing (elemIndex . head)

comparing takes a function that takes in two lists, and looks at the first element of each of our order lists, comparing the location.

sortLoc ords = sortBy (byLoc ords)

. , .

import Data.Maybe
import Data.List
sortLoc ords xs = mapMaybe lookup ords
  where lookup e = find ((==e) . head) xs

mapMaybe. , .

sortLoc ords xs = mapConcat lookup ords
  where lookup e = filter ((==e) . head) xs
+6

All Articles