Advertisement
banovski

List stats

Mar 28th, 2022 (edited)
1,366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Task: take a list and return a tuple with a number of items
  2. -- satisfying a predicate and a list of the items.
  3.  
  4. -- a verbose solution
  5. stats :: (a -> Bool) -> [a] -> (Int, [a])
  6. stats f xs = (count 0 f xs, filter f xs)
  7.   where
  8.     count a _ [] = a
  9.     count a f (x:xs)
  10.       | f x = count (a + 1) f xs
  11.       | otherwise = count a f xs
  12.  
  13. -- a terse solution
  14. stats :: (a -> Bool) -> [a] -> (Int, [a])
  15. stats f xs = (length sl, sl)
  16.   where
  17.     sl = filter f xs
  18.  
  19. -- stats (> 5) [0..9] → (4,[6,7,8,9])
  20.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement