HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Find the common elements of the lists in a list of lists

Submitted by: @import:stackexchange-codereview··
0
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:

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 $ xs


Is 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.