Skip to content

Commit 89a392f

Browse files
torgeirshtreeowl
authored andcommitted
Interleave effects better in chunksOf
Generalize the type of `chunksOf` to allow the inner and outer streams of the result to use different underlying monads. This forces effects to be handled within the inner monad, leading to an arguably better sort of chunking. Fixes #45
1 parent 7b12b30 commit 89a392f

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

changelog.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
Added `nubOrd` and friends.
44

5+
Generalized the type of `chunksOf` and made it handle effects better.
6+
(Thanks, Torgeir Strand Henriksen.)
7+
58
- 0.2.1.0
69

710
Adding `Semigroup` instances for GHC 8.4.

src/Streaming/Internal.hs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -722,12 +722,14 @@ takes n = void . splitsAt n
722722
2
723723
1
724724
-}
725-
chunksOf :: (Monad m, Functor f) => Int -> Stream f m r -> Stream (Stream f m) m r
726-
chunksOf n0 = loop where
727-
loop stream = case stream of
728-
Return r -> Return r
729-
Effect m -> Effect (fmap loop m)
730-
Step fs -> Step (Step (fmap (fmap loop . splitsAt (n0-1)) fs))
725+
chunksOf :: (Functor f, Monad m, Monad n) => Int -> Stream f m r -> Stream (Stream f m) n r
726+
chunksOf = go
727+
where
728+
go !n s = do
729+
stage <- yields $ lift . inspect =<< splitsAt n s
730+
case stage of
731+
Left r -> pure r
732+
Right s' -> go n $ wrap s'
731733
{-# INLINABLE chunksOf #-}
732734

733735
{- | Make it possible to \'run\' the underlying transformed monad.

0 commit comments

Comments
 (0)