Posted By

deepsoul on 10/06/11


Tagged

filter map


Versions (?)

Simultaneous filter and map


 / Published in: Haskell
 

The filtermap functional below allows to perform the standard map and filter operations in one go. The mapping function has to return a Maybe monad, and values of Nothing are filtered out.

  1. -- Prepend an element to a list if available. Leave the list as it is if the
  2. -- first argument is Nothing.
  3. maybecons :: Maybe t -> [t] -> [t]
  4. maybecons Nothing l = l
  5. maybecons (Just e) l = e : l
  6.  
  7. -- Variant of map which deletes elements if the map function returns Nothing.
  8. filtermap :: (a -> Maybe b) -> [a] -> [b]
  9. filtermap _ [] = []
  10. filtermap f (a:as) = maybecons (f a) $ filtermap f as

Report this snippet  

You need to login to post a comment.