[Solved] Comparison of two lists in Haskell


Edit: Another version suggested by David Young is

findIndicesIn xs ys = findIndices (`elem` ys) xs

which I prefer to my solution below.


If I understand correctly, you have two lists. Call them xs and ys. You want to find the index in xs of each element in ys. You don’t mention what you want to do if the element in ys is not contained in xs, so I am going to choose something reasonable for you. Here it is:

findIndicesIn :: Eq a => [a] -> [a] -> [Maybe Int]
findIndicesIn xs ys = map (`elemIndex` xs) ys

elemIndex :: Eq a => a -> [a] -> Maybe Int finds the index of the given element in the list (comparing with (==)). If the element does not exist, Nothing is returned instead. To find all the indices, we map over each element in ys and try to find it in xs using elemIndex. Section syntax is used instead of flip elemIndex xs or \y -> elemIndex y xs for concision.

The result is a list of Maybe Int representing the possible indices in xs of each element in ys. Note that if you do not keep track of missing elements, the positions of the indices in the resulting list will no longer correspond to the positions of the elements in ys.

You can also write this using fewer points as

findIndicesIn :: Eq a => [a] -> [a] -> [Maybe Int]
findIndicesIn xs = map (`elemIndex` xs)

YMMV on which one is more clear. Both are equivalent. This version is pretty readable IMO. You can go one step further and write

findIndicesIn = map . flip elemIndex

but personally I find this less readable. YMMV again.

14

solved Comparison of two lists in Haskell