Search code examples
haskellfunctional-programminglist-comprehension

Haskell - Checking if a list contains an element atleast N times


I am writing a function that checks if a list containts an element at least N times

atLeastNtimes :: Eq a => Int -> a -> [a] -> Bool
atLeastNtimes n a l = n <= (sum [1 | x <- l, (x == a)])

It is working fine with finite list, but I am struggling to make this work for infinite lists, for example:

atLeastNtimes 100 'a' (repeat 'a') 

Solution

  • Here are a few possible alternative approaches:

    • Define your function recursively, without ever trying to inspect the full list but only the needed prefix.

    • Start by filtering the list so to keep only the elements you want to count. Then, use drop (n-1) xs to drop n-1 elements (if any), and check if the resulting list is not empty (use null). Note that dropping more elements than those in the list is not an error, and it will result in an empty list.