Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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