Skip to content

Instantly share code, notes, and snippets.

@aristidb
Created December 27, 2011 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aristidb/1525471 to your computer and use it in GitHub Desktop.
Save aristidb/1525471 to your computer and use it in GitHub Desktop.
Possible Monad instance for Source?
sourceJoin :: Resource m => Source m (Source m a) -> Source m a
sourceJoin s = Source $ do
ps <- prepareSource s
innerSource <- newRef Nothing
let pull = do inner <- readRef innerSource
case inner of
Just x -> do st <- sourcePull x
case st of
Closed -> do pullFrom Nothing
Open vs -> return $ Open vs
Nothing -> do st <- sourcePull ps
case st of
Open xs -> do inner' <- prepareSource xs
pullFrom (Just inner')
Closed -> return Closed
pullFrom x = writeRef innerSource x >> pull
close = do maybe (return ()) sourceClose =<< readRef innerSource
sourceClose ps
return $ PreparedSource {
sourcePull = pull
, sourceClose = close
}
sourceReturn :: Resource m => a -> Source m a
sourceReturn x = sourceState True
(\s -> case s of
False -> return (False, Closed)
True -> return (False, Open x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment