patternMinor
Find the common elements of the lists in a list of lists
Viewed 0 times
findtheelementslistslistcommon
Problem
Considering the problem:
Make a function to find the common elements of the lists in a list of lists.
Example:
common ( [ [1,2,3,3,5,11], [2,2,2,3,3,5], [2,2,3,3,4,5,6,7,18,19], [3,5,10,15] ] ) = [3, 5].
I came up with this solution:
Is there a simpler way, more straightforward way that I'm missing? Perhaps in a library? How about the style?
Make a function to find the common elements of the lists in a list of lists.
Example:
common ( [ [1,2,3,3,5,11], [2,2,2,3,3,5], [2,2,3,3,4,5,6,7,18,19], [3,5,10,15] ] ) = [3, 5].
I came up with this solution:
import Data.List(group, nub, sort)
-- |
-- This function returns the elements common to all lists in a list of lists.
--
commonXss :: Ord a => [[a]] -> [a]
commonXss xss = concat [x | (x, y) [[a]] -> [([a], Int)]
countElemAppearsXss xss = freq $ sort $ concat $ map nub xss
-- |
-- This function returns a list of tuples. Each tuple (x, y) is made of
-- x == [element] and y == it's frequency.
--
freq :: Ord a => [a] -> [([a], Int)]
freq xs = map (\x -> ([head x], length x)) . group . sort $ xsIs there a simpler way, more straightforward way that I'm missing? Perhaps in a library? How about the style?
Solution
This problem is just a matter of folding using the
intersect function of Data.List, then deduplicating the result using nub.Context
StackExchange Code Review Q#87701, answer score: 3
Revisions (0)
No revisions yet.