@@ -1,4 +1,5 @@
11{-# LANGUAGE UndecidableInstances #-}
2+{-# OPTIONS_GHC -Wno-orphans #-}
23
34-- |
45-- Module : Streamly.Internal.Data.Stream.Serial
@@ -65,13 +66,15 @@ import Streamly.Internal.BaseCompat ((#.))
6566import Streamly.Internal.Data.Maybe.Strict (Maybe'(..), toMaybe)
6667import Streamly.Data.Stream (Stream)
6768
69+import qualified Streamly.Data.Fold as Fold
6870import qualified Streamly.Data.Stream as Stream
71+import qualified Streamly.Internal.Data.Stream as Stream (toStreamK, fromStreamK)
6972import qualified Streamly.Internal.Data.Stream.Common as P
7073import qualified Streamly.Internal.Data.Stream.StreamD as D
7174 (fromStreamK, toStreamK, mapM)
7275import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
73− (Stream, cons, consM, nil, concatMapWith, fromPure, bindWith
74− , withLocal, interleave, interleaveFst, interleaveMin)
76+ (Stream, mkStream, foldStream, cons, consM, nil, concatMapWith, fromPure
77+ , bindWith, interleave, interleaveFst, interleaveMin)
7578
7679import Prelude hiding (map, mapM, repeat, filter)
7780
@@ -83,6 +86,45 @@ import Prelude hiding (map, mapM, repeat, filter)
8386-- >>> import qualified Streamly.Data.Stream as Stream
8487-- >>> import qualified Streamly.Prelude as IsStream
8588
89+{-# INLINABLE withLocal #-}
90+withLocal :: MonadReader r m => (r -> r) -> K.Stream m a -> K.Stream m a
91+withLocal f m =
92+ K.mkStream $ \st yld sng stp ->
93+ let single = local f . sng
94+ yieldk a r = local f $ yld a (withLocal f r)
95+ in K.foldStream st yieldk single (local f stp) m
96+
97+------------------------------------------------------------------------------
98+-- mtl orphan instances
99+------------------------------------------------------------------------------
100+
101+instance (MonadReader r m) => MonadReader r (Stream m) where
102+ ask = lift ask
103+
104+ local f m = Stream.fromStreamK $ withLocal f (Stream.toStreamK m)
105+
106+instance (MonadState s m) => MonadState s (Stream m) where
107+ {-# INLINE get #-}
108+ get = lift get
109+
110+ {-# INLINE put #-}
111+ put x = lift (put x)
112+
113+ {-# INLINE state #-}
114+ state k = lift (state k)
115+
116+------------------------------------------------------------------------------
117+-- NFData - orphan instances
118+------------------------------------------------------------------------------
119+
120+instance NFData a => NFData (Stream Identity a) where
121+ {-# INLINE rnf #-}
122+ rnf xs = runIdentity $ Stream.fold (Fold.foldl' (\_ x -> rnf x) ()) xs
123+
124+instance NFData1 (Stream Identity) where
125+ {-# INLINE liftRnf #-}
126+ liftRnf f xs = runIdentity $ Stream.fold (Fold.foldl' (\_ x -> f x) ()) xs
127+
86128------------------------------------------------------------------------------
87129-- SerialT
88130------------------------------------------------------------------------------