public
Created

network-conduit vs monad transformer

  • Download Gist
gistfile1.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
{-# LANGUAGE PackageImports, TypeFamilies, FlexibleContexts #-}
 
-- code experiments with using monad stack with conduit
-- it works well except one case - using ResourceT in inner
-- monad (commented out function)
 
import Data.Conduit
import Data.Conduit.Network
import "mtl" Control.Monad.Reader
import "mtl" Control.Monad.Writer
import "mtl" Control.Monad.State
 
import Control.Monad.Trans.Resource (register)
 
data SInit = SInit Int deriving (Show,Eq)
data SState = SState Int deriving (Show,Eq)
 
main :: IO ()
main = do
let r = SInit 42
s = SState 3
flip runReaderT r $
flip runStateT s $
runTCPServer (ServerSettings 3500 Nothing) app
return ()
 
app ::
(Base m ~ IO,
MonadReader SInit m,
MonadIO m,
IsSource src,
Resource m
) =>
src m a1 -> Sink a1 m b -> ResourceT m b
app src snk = src $= (process1 =$= process2 {-=$= process3-}) $$ snk
where
process1 = self
where
self = Conduit push close
push item = do
r <- lift ask
liftIO $ print r
register $ putStrLn "freed"
return $ Producing self [item]
close = return []
process2 = self
where
self = Conduit push close
push item = do
r <- lift ask
-- using reader, ok
(k,t) <- runWriterT $ do {- 1 -}
x <- (lift . lift) ask
tell [x]
return ()
-- using reader and IO
(k,t) <- runWriterT $ do {- 2 -}
(SInit x) <- (lift . lift) ask
liftIO $ print $ x + 1
tell [x]
-- using reader, IO and register, failed
(k,t) <- runWriterT $ do {- 3 -}
(SInit x) <- (lift . lift) ask
liftIO $ print $x+1
lift $ register $ print "freed2"
tell [x]
return $ Producing self [item]
close = return []

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.