on master help sign in
Add Foldable and Traversable instances for StreamD and StreamK
commit977c344600cb7ef1555ef8c4f4d0279e21ca51f0 authorAbhiroop Sarkar <asiamgenius@gmail.com> dateFri 2 Nov 2018, 14:08 (8 years ago) parentc7666a7
2 files changed+31
src/Streamly/Streams/StreamD.hs+16 src/Streamly/Streams/StreamK.hs+15
src/Streamly/Streams/StreamD.hs+16
@@ -127,6 +127,8 @@ import Prelude
127127 notElem, null, head, tail, zipWith)
128128
129129import Streamly.SVar (MonadAsync, State(..), defState, rstState)
130+
131+import qualified Data.Foldable as F
130132import qualified Streamly.Streams.StreamK as K
131133
132134------------------------------------------------------------------------------
@@ -148,6 +150,20 @@ instance Functor (Step s) where
148150-- current state, and the current state.
149151data Stream m a = forall s. Stream (State K.Stream m a -> s -> m (Step s a)) s
150152
153+instance (Foldable m, Monad m) => Foldable (Stream m) where
154+ {-# INLINE foldMap #-}
155+ foldMap f = F.fold . toFoldable . map f
156+ where
157+ toFoldable :: (Monad m, Monoid a) => Stream m a -> m a
158+ toFoldable = foldr mappend mempty
159+
160+instance (Traversable m, Monad m) => Traversable (Stream m) where
161+ {-# INLINE traverse #-}
162+ traverse f = sequenceA . fmap f
163+
164+ {-# INLINE sequenceA #-}
165+ sequenceA = traverse id
166+
151167------------------------------------------------------------------------------
152168-- Construction
153169------------------------------------------------------------------------------
src/Streamly/Streams/StreamK.hs+15
@@ -153,6 +153,7 @@ import Prelude
153153 take, filter, all, any, takeWhile, drop, dropWhile, minimum,
154154 maximum, elem, notElem, null, head, tail, init, zipWith, lookup,
155155 foldr1)
156+import qualified Data.Foldable as F
156157import qualified Prelude
157158
158159import Streamly.SVar
@@ -188,6 +189,20 @@ newtype Stream m a =
188189 -> m r
189190 }
190191
192+instance (Foldable m, Monad m) => Foldable (Stream m) where
193+ {-# INLINE foldMap #-}
194+ foldMap f = F.fold . toFoldable . map f
195+ where
196+ toFoldable :: (Monad m, Monoid a) => Stream m a -> m a
197+ toFoldable = foldr mappend mempty
198+
199+instance (Traversable m, Monad m) => Traversable (Stream m) where
200+ {-# INLINE traverse #-}
201+ traverse f = sequenceA . fmap f
202+
203+ {-# INLINE sequenceA #-}
204+ sequenceA = traverse id
205+
191206-- XXX make this the default "unStream"
192207-- | unwraps the Stream type producing the stream function that can be run with
193208-- continuations.