Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created December 15, 2010 09:42
Show Gist options
  • Save thsutton/741815 to your computer and use it in GitHub Desktop.
Save thsutton/741815 to your computer and use it in GitHub Desktop.
A first attempt at making an enumeratee equivalent to the filter function for lists.
import Prelude hiding (sequence, map, head, filter)
import Control.Monad.Trans (lift, MonadIO, liftIO)
import Data.Enumerator
-- | Enumerator analogue of 'Data.List.filter'.
filter :: Monad m => (a -> Bool) -> Enumeratee a a m b
filter pred (Continue k) = do
x <- head
case x of
Nothing -> return $ Continue k
Just y -> do
newStep <- if (pred y)
then lift $ runIteratee $ k $ Chunks [y]
else lift $ runIteratee $ k $ Chunks []
filter pred newStep
filter pred step = return step
-- | Enumerator analogue of 'Control.Monad.filterM'.
filterM :: Monad m => (a -> (m Bool)) -> Enumeratee a a m b
filterM pred (Continue k) = do
x <- head
case x of
Nothing -> return $ Continue k
Just y -> do
valid <- lift $ pred y
newStep <- if valid
then lift $ runIteratee $ k $ Chunks [y]
else lift $ runIteratee $ k $ Chunks []
filterM pred newStep
filterM pred step = return step
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment