title: How to optimize filtering of a list
body: <p>To learn Haskell I've been solving programming challenges. While trying to solve one problem found in Hackerrank about filtering elements of a list of thousand of elements, I've been unable to pass the time tests.</p>
  
  <p><strong>The problem statement is</strong>: from a list of elements filter those that appear more than <strong>k</strong> times and print them in their order of appearance.</p>
  
  <p>The best I've come so far is this code:</p>
  
  <pre><code>import qualified Data.ByteString.Char8 as BSC
  import Data.Maybe (fromJust)
  import Data.List (intercalate, elemIndices, foldl')
  import qualified Data.Set as S
  
  -- Improved version of nub
  nub' :: (Ord a) =&gt; [a] -&gt; [a]
  nub' = go S.empty
    where go _ [] = []
          go s (x:xs) | S.member x s = go s xs
                      | otherwise    = x : go (S.insert x s) xs
  
  -- Extract Int from ByteString     
  getIntFromBS :: BSC.ByteString -&gt; Int
  getIntFromBS = fst . fromJust . BSC.readInt
  
  {- 
      Parse read file:
  
      a k1
      n1 n2 n3 n4 ... 
      c k2
      m1 m2 m3 m4 ...
  
      into appropriate format:
  
      [(k1, [n1,n2,n3,n4]), (k2, [m1,m2,m3,m4])]
  -}
  createGroups :: [BSC.ByteString] -&gt; [(Int, [Int])]
  createGroups [] = []
  createGroups (p:v:xs) =
      let val = getIntFromBS $ last $ BSC.split ' ' p
          grp = foldr (\x acc -&gt; getIntFromBS x : acc) [] $ BSC.split ' ' v
      in (val, grp) : createGroups xs
  
  solve :: (Int, [Int]) -&gt; String
  solve (k, v) = intercalate " " $ if null res then ["-1"] else res
      where
          go n acc =
              if length (elemIndices n v) &gt; k
                  then show n : acc
                  else          acc
          res = foldr go [] (nub' v)
  
  fullSolve :: [BSC.ByteString] -&gt; [String]
  fullSolve xs = foldl' (\acc tupla -&gt; acc ++ [solve tupla]) [] $ createGroups xs
  
  main = do
      BSC.getContents &gt;&gt;= mapM_ putStrLn . fullSolve . drop 1 . BSC.lines
  </code></pre>
  
  <p>I would like to know where can I improve this code. I've tried many variants using maps,vectors, parsing and not parsing the read strings from the file to <code>Int</code>, but the shown code is the best I have.</p>