Simultaneous filter and map


/ Published in: Haskell
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.