Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only keep values that appear more than once within a list comprehension

For example, if I have a list comprehension

comp :: Int -> Int -> Int -> [Int]
comp xs a b = [ y | x <- xs, y <- (func x a b) ]

where func is just the function

func :: Int -> Int -> Int -> [Int]
func x a b
   | (x == a || x == b  = [a,b]
   | otherwise          = filter (/=a) [a,b])

comp will typically give me duplicate values due to the way my func works.

i.e. I might get comp = [1,2,2,3,3,4] when passing some arbitrary a and b.

My question is: Is there any way I can only keep values in this list that appear more than once within the list comprehension? So that I instead get comp = [2,3] (since 2 and 3 appear more than once).

I understand there are many ways to do it outside of the list comprehension, but I want to know if it is possible to do it inside. Or could I even use a helper function to do this?

like image 292
pylab Avatar asked Dec 10 '25 20:12

pylab


1 Answers

Yes, with the help of group:

import Data.List

onlyDupes xs = [x | x:_:_ <- group xs]

It works like this:

λ> onlyDupes [1,2,2,3,3,4]
[2,3]

You could integrate that logic into your existing list comprehension like this:

comp xs a b = [ y | x <- xs, y:_:_ <- group (func x a b) ]

Note: if your values aren't always sorted like they are in your example, then you'll need to use (group . sort) instead of just group.

like image 62
Joseph Sible-Reinstate Monica Avatar answered Dec 13 '25 08:12

Joseph Sible-Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!