-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathStreamK.hs
More file actions
1397 lines (1245 loc) · 46.6 KB
/
StreamK.hs
File metadata and controls
1397 lines (1245 loc) · 46.6 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE CPP #-}
{- HLINT ignore "Eta reduce" -}
-- |
-- Module : Streamly.Internal.Data.StreamK
-- Copyright : (c) 2017 Composewell Technologies
--
-- License : BSD3
-- Maintainer : streamly@composewell.com
-- Stability : experimental
-- Portability : GHC
--
module Streamly.Internal.Data.StreamK
(
-- * Setup
-- | To execute the code examples provided in this module in ghci, please
-- run the following commands first.
--
-- $setup
module Streamly.Internal.Data.StreamK.Type
-- * Transformer
, module Streamly.Internal.Data.StreamK.Transformer
-- * From containers
, fromStream
-- * Specialized Generation
, repeatM
, replicate
, replicateM
, fromIndices
, fromIndicesM
, iterate
, iterateM
-- * Elimination
-- ** General Folds
, foldr1
, fold
, foldBreak
, foldEither
, foldConcat
, ParserK.toParserK -- XXX move the code to this module
, parseDBreak
, parseD
, parseBreak
, parseBreakPos
, parse
, parsePos
-- ** Specialized Folds
, head
, elem
, notElem
, all
, any
, last
, minimum
, minimumBy
, maximum
, maximumBy
, findIndices
, lookup
, findM
, find
, (!!)
-- ** To Containers
, toList
, toStream
-- ** Map and Fold
, mapM_
-- * Transformation
-- ** By folding (scans)
, scanl'
, scanlx'
-- ** Filtering
, filter
, take
, takeWhile
, drop
, dropWhile
-- ** Mapping
, mapM
, sequence
-- ** Inserting
, intersperseM
, intersperse
, insertBy
-- ** Deleting
, deleteBy
-- ** Reordering
, sortBy
, sortOn
-- ** Map and Filter
, mapMaybe
-- ** Zipping
, zipWith
, zipWithM
-- ** Merging
, mergeBy
, mergeByM
-- ** Transformation comprehensions
, the
-- ** Transforming Inner Monad
, morphInner
-- * Exceptions
, handle
-- * Resource Management
, bracketIO
-- * Deprecated
, hoist
, parseBreakChunks
, parseChunks
, parseBreakChunksGeneric
, parseChunksGeneric
)
where
#include "ArrayMacros.h"
#include "inline.hs"
#include "assert.hs"
#include "deprecation.h"
import Control.Exception (mask_, Exception)
import Control.Monad (void, join)
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Ord (comparing)
import GHC.Types (SPEC(..))
import Streamly.Internal.Data.Array.Type (Array(..))
import Streamly.Internal.Data.Fold.Type (Fold(..))
import Streamly.Internal.Data.IOFinalizer (newIOFinalizer, runIOFinalizer)
import Streamly.Internal.Data.ParserK.Type (ParserK)
import Streamly.Internal.Data.Producer.Type (Producer(..))
import Streamly.Internal.Data.SVar.Type (adaptState, defState)
import Streamly.Internal.Data.Unbox (Unbox)
import qualified Control.Monad.Catch as MC
import qualified Streamly.Internal.Data.Array as Array
import qualified Streamly.Internal.Data.Array.Generic as GenArr
import qualified Streamly.Internal.Data.Fold.Type as FL
import qualified Streamly.Internal.Data.Parser as Parser
import qualified Streamly.Internal.Data.ParserDrivers as Drivers
import qualified Streamly.Internal.Data.Parser.Type as PR
import qualified Streamly.Internal.Data.ParserK.Type as ParserK
import qualified Streamly.Internal.Data.Stream as Stream
import qualified Prelude
import Prelude
hiding (Foldable(..), last, map, mapM, mapM_, repeat, sequence,
take, filter, all, any, takeWhile, drop, dropWhile,
notElem, head, tail, init, zipWith, lookup,
(!!), replicate, reverse, concatMap, iterate, splitAt)
import Data.Foldable (length)
import Streamly.Internal.Data.StreamK.Type
import Streamly.Internal.Data.StreamK.Transformer
import Streamly.Internal.Data.Parser (ParseError(..), ParseErrorPos(..))
#include "DocTestDataStreamK.hs"
-- | Convert a fused 'Stream' to 'StreamK'.
--
-- For example:
--
-- >>> s1 = StreamK.fromStream $ Stream.fromList [1,2]
-- >>> s2 = StreamK.fromStream $ Stream.fromList [3,4]
-- >>> Stream.fold Fold.toList $ StreamK.toStream $ s1 `StreamK.append` s2
-- [1,2,3,4]
--
{-# INLINE fromStream #-}
fromStream :: Monad m => Stream.Stream m a -> StreamK m a
fromStream = Stream.toStreamK
-- | Convert a 'StreamK' to a fused 'Stream'.
--
{-# INLINE toStream #-}
toStream :: Applicative m => StreamK m a -> Stream.Stream m a
toStream = Stream.fromStreamK
-------------------------------------------------------------------------------
-- Generation
-------------------------------------------------------------------------------
{-
-- Generalization of concurrent streams/SVar via unfoldr.
--
-- Unfold a value into monadic actions and then run the resulting monadic
-- actions to generate a stream. Since the step of generating the monadic
-- action and running them are decoupled we can run the monadic actions
-- cooncurrently. For example, the seed could be a list of monadic actions or a
-- pure stream of monadic actions.
--
-- We can have different flavors of this depending on the stream type t. The
-- concurrent version could be async or ahead etc. Depending on how we queue
-- back the feedback portion b, it could be DFS or BFS style.
--
unfoldrA :: (b -> Maybe (m a, b)) -> b -> StreamK m a
unfoldrA = undefined
-}
-------------------------------------------------------------------------------
-- Special generation
-------------------------------------------------------------------------------
-- |
-- >>> repeatM = StreamK.sequence . StreamK.repeat
-- >>> repeatM = fix . StreamK.consM
-- >>> repeatM = cycle1 . StreamK.fromEffect
--
-- Generate a stream by repeatedly executing a monadic action forever.
--
-- >>> :{
-- repeatAction =
-- StreamK.repeatM (threadDelay 1000000 >> print 1)
-- & StreamK.take 10
-- & StreamK.fold Fold.drain
-- :}
--
repeatM :: Monad m => m a -> StreamK m a
repeatM = repeatMWith consM
{-# INLINE replicateM #-}
replicateM :: Monad m => Int -> m a -> StreamK m a
replicateM = replicateMWith consM
{-# INLINE replicate #-}
replicate :: Int -> a -> StreamK m a
replicate n a = go n
where
go cnt = if cnt <= 0 then nil else a `cons` go (cnt - 1)
{-# INLINE fromIndicesM #-}
fromIndicesM :: Monad m => (Int -> m a) -> StreamK m a
fromIndicesM = fromIndicesMWith consM
{-# INLINE fromIndices #-}
fromIndices :: (Int -> a) -> StreamK m a
fromIndices gen = go 0
where
go n = gen n `cons` go (n + 1)
-- |
-- >>> iterate f x = x `StreamK.cons` iterate f x
--
-- Generate an infinite stream with @x@ as the first element and each
-- successive element derived by applying the function @f@ on the previous
-- element.
--
-- >>> StreamK.toList $ StreamK.take 5 $ StreamK.iterate (+1) 1
-- [1,2,3,4,5]
--
{-# INLINE iterate #-}
iterate :: (a -> a) -> a -> StreamK m a
iterate step = go
where
go !s = cons s (go (step s))
-- |
-- >>> iterateM f m = m >>= \a -> return a `StreamK.consM` iterateM f (f a)
--
-- Generate an infinite stream with the first element generated by the action
-- @m@ and each successive element derived by applying the monadic function
-- @f@ on the previous element.
--
-- >>> :{
-- StreamK.iterateM (\x -> print x >> return (x + 1)) (return 0)
-- & StreamK.take 3
-- & StreamK.toList
-- :}
-- 0
-- 1
-- [0,1,2]
--
{-# INLINE iterateM #-}
iterateM :: Monad m => (a -> m a) -> m a -> StreamK m a
iterateM = iterateMWith consM
-------------------------------------------------------------------------------
-- Elimination by Folding
-------------------------------------------------------------------------------
{-# INLINE foldr1 #-}
foldr1 :: Monad m => (a -> a -> a) -> StreamK m a -> m (Maybe a)
foldr1 step m = do
r <- uncons m
case r of
Nothing -> return Nothing
Just (h, t) -> fmap Just (go h t)
where
go p m1 =
let stp = return p
single a = return $ step a p
yieldk a r = fmap (step p) (go a r)
in foldStream defState yieldk single stp m1
-- | Fold a stream using the supplied left 'Fold' and reducing the resulting
-- expression strictly at each step. The behavior is similar to 'foldl''. A
-- 'Fold' can terminate early without consuming the full stream. See the
-- documentation of individual 'Fold's for termination behavior.
--
-- Definitions:
--
-- >>> fold f = fmap fst . StreamK.foldBreak f
-- >>> fold f = StreamK.parseD (Parser.fromFold f)
--
-- Example:
--
-- >>> StreamK.fold Fold.sum $ StreamK.fromStream $ Stream.enumerateFromTo 1 100
-- 5050
--
{-# INLINABLE fold #-}
fold :: Monad m => FL.Fold m a b -> StreamK m a -> m b
fold (FL.Fold step begin _ final) m = do
res <- begin
case res of
FL.Partial fs -> go fs m
FL.Done fb -> return fb
where
go !acc m1 =
let stop = final acc
single a = step acc a
>>= \case
FL.Partial s -> final s
FL.Done b1 -> return b1
yieldk a r = step acc a
>>= \case
FL.Partial s -> go s r
FL.Done b1 -> return b1
in foldStream defState yieldk single stop m1
-- | Fold resulting in either breaking the stream or continuation of the fold.
-- Instead of supplying the input stream in one go we can run the fold multiple
-- times, each time supplying the next segment of the input stream. If the fold
-- has not yet finished it returns a fold that can be run again otherwise it
-- returns the fold result and the residual stream.
--
-- /Internal/
{-# INLINE foldEither #-}
foldEither :: Monad m =>
Fold m a b -> StreamK m a -> m (Either (Fold m a b) (b, StreamK m a))
foldEither (FL.Fold step begin done final) m = do
res <- begin
case res of
FL.Partial fs -> go fs m
FL.Done fb -> return $ Right (fb, m)
where
go !acc m1 =
let stop =
let f = Fold step (return $ FL.Partial acc) done final
in return $ Left f
single a =
step acc a
>>= \case
FL.Partial s ->
let f = Fold step (return $ FL.Partial s) done final
in return $ Left f
FL.Done b1 -> return $ Right (b1, nil)
yieldk a r =
step acc a
>>= \case
FL.Partial s -> go s r
FL.Done b1 -> return $ Right (b1, r)
in foldStream defState yieldk single stop m1
-- | Like 'fold' but also returns the remaining stream. The resulting stream
-- would be 'StreamK.nil' if the stream finished before the fold.
--
{-# INLINE foldBreak #-}
foldBreak :: Monad m => Fold m a b -> StreamK m a -> m (b, StreamK m a)
foldBreak fld strm = do
r <- foldEither fld strm
case r of
Right res -> return res
Left (Fold _ initial _ final) -> do
res <- initial
case res of
FL.Done _ -> error "foldBreak: unreachable state"
FL.Partial s -> do
b <- final s
return (b, nil)
-- XXX Array folds can be implemented using this.
-- foldContainers? Specialized to foldArrays.
-- | Generate streams from individual elements of a stream and fold the
-- concatenation of those streams using the supplied fold. Return the result of
-- the fold and residual stream.
--
-- For example, this can be used to efficiently fold an Array Word8 stream
-- using Word8 folds.
--
-- /Internal/
{-# INLINE foldConcat #-}
foldConcat :: Monad m =>
Producer m a b -> Fold m b c -> StreamK m a -> m (c, StreamK m a)
foldConcat
(Producer pstep pinject pextract)
(Fold fstep begin _ final)
stream = do
res <- begin
case res of
FL.Partial fs -> go fs stream
FL.Done fb -> return (fb, stream)
where
go !acc m1 = do
let stop = do
r <- final acc
return (r, nil)
single a = do
st <- pinject a
res <- go1 SPEC acc st
case res of
Left fs -> do
r <- final fs
return (r, nil)
Right (b, s) -> do
x <- pextract s
return (b, fromPure x)
yieldk a r = do
st <- pinject a
res <- go1 SPEC acc st
case res of
Left fs -> go fs r
Right (b, s) -> do
x <- pextract s
return (b, x `cons` r)
in foldStream defState yieldk single stop m1
{-# INLINE go1 #-}
go1 !_ !fs st = do
r <- pstep st
case r of
Stream.Yield x s -> do
res <- fstep fs x
case res of
FL.Done b -> return $ Right (b, s)
FL.Partial fs1 -> go1 SPEC fs1 s
Stream.Skip s -> go1 SPEC fs s
Stream.Stop -> return $ Left fs
------------------------------------------------------------------------------
-- Specialized folds
------------------------------------------------------------------------------
{-# INLINE head #-}
head :: Monad m => StreamK m a -> m (Maybe a)
-- head = foldrM (\x _ -> return $ Just x) (return Nothing)
head m =
let stop = return Nothing
single a = return (Just a)
yieldk a _ = return (Just a)
in foldStream defState yieldk single stop m
{-# INLINE elem #-}
elem :: (Monad m, Eq a) => a -> StreamK m a -> m Bool
elem e = go
where
go m1 =
let stop = return False
single a = return (a == e)
yieldk a r = if a == e then return True else go r
in foldStream defState yieldk single stop m1
{-# INLINE notElem #-}
notElem :: (Monad m, Eq a) => a -> StreamK m a -> m Bool
notElem e = go
where
go m1 =
let stop = return True
single a = return (a /= e)
yieldk a r = if a == e then return False else go r
in foldStream defState yieldk single stop m1
{-# INLINABLE all #-}
all :: Monad m => (a -> Bool) -> StreamK m a -> m Bool
all p = go
where
go m1 =
let single a | p a = return True
| otherwise = return False
yieldk a r | p a = go r
| otherwise = return False
in foldStream defState yieldk single (return True) m1
{-# INLINABLE any #-}
any :: Monad m => (a -> Bool) -> StreamK m a -> m Bool
any p = go
where
go m1 =
let single a | p a = return True
| otherwise = return False
yieldk a r | p a = return True
| otherwise = go r
in foldStream defState yieldk single (return False) m1
-- | Extract the last element of the stream, if any.
{-# INLINE last #-}
last :: Monad m => StreamK m a -> m (Maybe a)
last = foldlx' (\_ y -> Just y) Nothing id
{-# INLINE minimum #-}
minimum :: (Monad m, Ord a) => StreamK m a -> m (Maybe a)
minimum = go Nothing
where
go Nothing m1 =
let stop = return Nothing
single a = return (Just a)
yieldk a r = go (Just a) r
in foldStream defState yieldk single stop m1
go (Just res) m1 =
let stop = return (Just res)
single a =
if res <= a
then return (Just res)
else return (Just a)
yieldk a r =
if res <= a
then go (Just res) r
else go (Just a) r
in foldStream defState yieldk single stop m1
{-# INLINE minimumBy #-}
minimumBy
:: (Monad m)
=> (a -> a -> Ordering) -> StreamK m a -> m (Maybe a)
minimumBy cmp = go Nothing
where
go Nothing m1 =
let stop = return Nothing
single a = return (Just a)
yieldk a r = go (Just a) r
in foldStream defState yieldk single stop m1
go (Just res) m1 =
let stop = return (Just res)
single a = case cmp res a of
GT -> return (Just a)
_ -> return (Just res)
yieldk a r = case cmp res a of
GT -> go (Just a) r
_ -> go (Just res) r
in foldStream defState yieldk single stop m1
{-# INLINE maximum #-}
maximum :: (Monad m, Ord a) => StreamK m a -> m (Maybe a)
maximum = go Nothing
where
go Nothing m1 =
let stop = return Nothing
single a = return (Just a)
yieldk a r = go (Just a) r
in foldStream defState yieldk single stop m1
go (Just res) m1 =
let stop = return (Just res)
single a =
if res <= a
then return (Just a)
else return (Just res)
yieldk a r =
if res <= a
then go (Just a) r
else go (Just res) r
in foldStream defState yieldk single stop m1
{-# INLINE maximumBy #-}
maximumBy :: Monad m => (a -> a -> Ordering) -> StreamK m a -> m (Maybe a)
maximumBy cmp = go Nothing
where
go Nothing m1 =
let stop = return Nothing
single a = return (Just a)
yieldk a r = go (Just a) r
in foldStream defState yieldk single stop m1
go (Just res) m1 =
let stop = return (Just res)
single a = case cmp res a of
GT -> return (Just res)
_ -> return (Just a)
yieldk a r = case cmp res a of
GT -> go (Just res) r
_ -> go (Just a) r
in foldStream defState yieldk single stop m1
{-# INLINE (!!) #-}
(!!) :: Monad m => StreamK m a -> Int -> m (Maybe a)
m !! i = go i m
where
go n m1 =
let single a | n == 0 = return $ Just a
| otherwise = return Nothing
yieldk a x | n < 0 = return Nothing
| n == 0 = return $ Just a
| otherwise = go (n - 1) x
in foldStream defState yieldk single (return Nothing) m1
{-# INLINE lookup #-}
lookup :: (Monad m, Eq a) => a -> StreamK m (a, b) -> m (Maybe b)
lookup e = go
where
go m1 =
let single (a, b) | a == e = return $ Just b
| otherwise = return Nothing
yieldk (a, b) x | a == e = return $ Just b
| otherwise = go x
in foldStream defState yieldk single (return Nothing) m1
{-# INLINE findM #-}
findM :: Monad m => (a -> m Bool) -> StreamK m a -> m (Maybe a)
findM p = go
where
go m1 =
let single a = do
b <- p a
if b then return $ Just a else return Nothing
yieldk a x = do
b <- p a
if b then return $ Just a else go x
in foldStream defState yieldk single (return Nothing) m1
{-# INLINE find #-}
find :: Monad m => (a -> Bool) -> StreamK m a -> m (Maybe a)
find p = findM (return . p)
{-# INLINE findIndices #-}
findIndices :: (a -> Bool) -> StreamK m a -> StreamK m Int
findIndices p = go 0
where
go offset m1 = mkStream $ \st yld sng stp ->
let single a | p a = sng offset
| otherwise = stp
yieldk a x | p a = yld offset $ go (offset + 1) x
| otherwise = foldStream (adaptState st) yld sng stp $
go (offset + 1) x
in foldStream (adaptState st) yieldk single stp m1
------------------------------------------------------------------------------
-- Map and Fold
------------------------------------------------------------------------------
-- | Apply a monadic action to each element of the stream and discard the
-- output of the action.
{-# INLINE mapM_ #-}
mapM_ :: Monad m => (a -> m b) -> StreamK m a -> m ()
mapM_ f = go
where
go m1 =
let stop = return ()
single a = void (f a)
yieldk a r = f a >> go r
in foldStream defState yieldk single stop m1
{-# INLINE mapM #-}
mapM :: Monad m => (a -> m b) -> StreamK m a -> StreamK m b
mapM = mapMWith consM
------------------------------------------------------------------------------
-- Converting folds
------------------------------------------------------------------------------
{-# INLINABLE toList #-}
toList :: Monad m => StreamK m a -> m [a]
toList = foldr (:) []
-- Based on suggestions by David Feuer and Pranay Sashank
{-# INLINE morphInner #-}
morphInner, hoist :: (Monad m, Monad n)
=> (forall x. m x -> n x) -> StreamK m a -> StreamK n a
morphInner f str =
mkStream $ \st yld sng stp ->
let single = return . sng
yieldk a s = return $ yld a (hoist f s)
stop = return stp
state = adaptState st
in join . f $ foldStreamShared state yieldk single stop str
RENAME(hoist,morphInner)
-------------------------------------------------------------------------------
-- Transformation by folding (Scans)
-------------------------------------------------------------------------------
{-# INLINE scanlx' #-}
scanlx' :: (x -> a -> x) -> x -> (x -> b) -> StreamK m a -> StreamK m b
scanlx' step begin done m =
cons (done begin) $ go m begin
where
go m1 !acc = mkStream $ \st yld sng stp ->
let single a = sng (done $ step acc a)
yieldk a r =
let s = step acc a
in yld (done s) (go r s)
in foldStream (adaptState st) yieldk single stp m1
{-# INLINE scanl' #-}
scanl' :: (b -> a -> b) -> b -> StreamK m a -> StreamK m b
scanl' step begin = scanlx' step begin id
-------------------------------------------------------------------------------
-- Filtering
-------------------------------------------------------------------------------
{-# INLINE filter #-}
filter :: (a -> Bool) -> StreamK m a -> StreamK m a
filter p = go
where
go m1 = mkStream $ \st yld sng stp ->
let single a | p a = sng a
| otherwise = stp
yieldk a r | p a = yld a (go r)
| otherwise = foldStream st yieldk single stp r
in foldStream st yieldk single stp m1
{-# INLINE take #-}
take :: Int -> StreamK m a -> StreamK m a
take = go
where
go n1 m1 = mkStream $ \st yld sng stp ->
let yieldk a r = yld a (go (n1 - 1) r)
in if n1 <= 0
then stp
else foldStream st yieldk sng stp m1
{-# INLINE takeWhile #-}
takeWhile :: (a -> Bool) -> StreamK m a -> StreamK m a
takeWhile p = go
where
go m1 = mkStream $ \st yld sng stp ->
let single a | p a = sng a
| otherwise = stp
yieldk a r | p a = yld a (go r)
| otherwise = stp
in foldStream st yieldk single stp m1
{-# INLINE drop #-}
drop :: Int -> StreamK m a -> StreamK m a
drop n m = unShare (go n m)
where
go n1 m1 = mkStream $ \st yld sng stp ->
let single _ = stp
yieldk _ r = foldStreamShared st yld sng stp $ go (n1 - 1) r
-- Somehow "<=" check performs better than a ">"
in if n1 <= 0
then foldStreamShared st yld sng stp m1
else foldStreamShared st yieldk single stp m1
{-# INLINE dropWhile #-}
dropWhile :: (a -> Bool) -> StreamK m a -> StreamK m a
dropWhile p = go
where
go m1 = mkStream $ \st yld sng stp ->
let single a | p a = stp
| otherwise = sng a
yieldk a r | p a = foldStream st yieldk single stp r
| otherwise = yld a r
in foldStream st yieldk single stp m1
-------------------------------------------------------------------------------
-- Mapping
-------------------------------------------------------------------------------
-- Be careful when modifying this, this uses a consM (|:) deliberately to allow
-- other stream types to overload it.
{-# INLINE sequence #-}
sequence :: Monad m => StreamK m (m a) -> StreamK m a
sequence = go
where
go m1 = mkStream $ \st yld sng stp ->
let single ma = ma >>= sng
yieldk ma r = foldStreamShared st yld sng stp $ ma `consM` go r
in foldStream (adaptState st) yieldk single stp m1
-------------------------------------------------------------------------------
-- Inserting
-------------------------------------------------------------------------------
{-# INLINE intersperseM #-}
intersperseM :: Monad m => m a -> StreamK m a -> StreamK m a
intersperseM a = prependingStart
where
prependingStart m1 = mkStream $ \st yld sng stp ->
let yieldk i x =
foldStreamShared st yld sng stp $ return i `consM` go x
in foldStream st yieldk sng stp m1
go m2 = mkStream $ \st yld sng stp ->
let single i = foldStreamShared st yld sng stp $ a `consM` fromPure i
yieldk i x =
foldStreamShared
st yld sng stp $ a `consM` return i `consM` go x
in foldStream st yieldk single stp m2
{-# INLINE intersperse #-}
intersperse :: Monad m => a -> StreamK m a -> StreamK m a
intersperse a = intersperseM (return a)
{-# INLINE insertBy #-}
insertBy :: (a -> a -> Ordering) -> a -> StreamK m a -> StreamK m a
insertBy cmp x = go
where
go m1 = mkStream $ \st yld _ _ ->
let single a = case cmp x a of
GT -> yld a (fromPure x)
_ -> yld x (fromPure a)
stop = yld x nil
yieldk a r = case cmp x a of
GT -> yld a (go r)
_ -> yld x (a `cons` r)
in foldStream st yieldk single stop m1
------------------------------------------------------------------------------
-- Deleting
------------------------------------------------------------------------------
{-# INLINE deleteBy #-}
deleteBy :: (a -> a -> Bool) -> a -> StreamK m a -> StreamK m a
deleteBy eq x = go
where
go m1 = mkStream $ \st yld sng stp ->
let single a = if eq x a then stp else sng a
yieldk a r = if eq x a
then foldStream st yld sng stp r
else yld a (go r)
in foldStream st yieldk single stp m1
-------------------------------------------------------------------------------
-- Map and Filter
-------------------------------------------------------------------------------
{-# INLINE mapMaybe #-}
mapMaybe :: (a -> Maybe b) -> StreamK m a -> StreamK m b
mapMaybe f = go
where
go m1 = mkStream $ \st yld sng stp ->
let single a = maybe stp sng (f a)
yieldk a r = case f a of
Just b -> yld b $ go r
Nothing -> foldStream (adaptState st) yieldk single stp r
in foldStream (adaptState st) yieldk single stp m1
-------------------------------------------------------------------------------
-- Exception Handling
-------------------------------------------------------------------------------
-- | Like Streamly.Data.Stream.'Streamly.Data.Stream.handle' but with one
-- significant difference, this function observes exceptions from the consumer
-- of the stream as well.
--
-- You can also convert 'StreamK' to 'Stream' and use exception handling from
-- 'Stream' module:
--
-- >>> handle f s = StreamK.fromStream $ Stream.handle (\e -> StreamK.toStream (f e)) (StreamK.toStream s)
--
{-# INLINABLE handle #-}
handle :: (MonadCatch m, Exception e)
=> (e -> m (StreamK m a)) -> StreamK m a -> StreamK m a
handle f stream = go stream
where
go m1 = mkStream $ \st yld sng stp ->
let yieldk a r = yld a $ go r
in do
res <- MC.try (foldStream (adaptState st) yieldk sng stp m1)
case res of
Right r -> return r
Left e -> do
r <- f e
foldStream (adaptState st) yld sng stp r
-------------------------------------------------------------------------------
-- Resource Management
-------------------------------------------------------------------------------
-- If we are folding the stream and we do not drain the entire stream (e.g. if
-- the fold terminates before the stream) then the finalizer will run on GC.
--
-- XXX To implement a prompt cleanup, we will have to yield a cleanup function
-- via the yield continuation. A chain of cleanup functions can be built and
-- the entire chain can be invoked when the stream ends voluntarily or if
-- someone decides to abandon the stream.
-- | Like Streamly.Data.Stream.'Streamly.Data.Stream.bracketIO' but with one
-- significant difference, this function observes exceptions from the consumer
-- of the stream as well. Therefore, it cleans up the resource promptly when
-- the consumer encounters an exception.
--
-- You can also convert 'StreamK' to 'Stream' and use resource handling from
-- 'Stream' module:
--
-- >>> bracketIO bef aft bet = StreamK.fromStream $ Stream.bracketIO bef aft (StreamK.toStream . bet)
--
{-# INLINABLE bracketIO #-}
bracketIO :: (MonadIO m, MonadCatch m)
=> IO b -> (b -> IO c) -> (b -> StreamK m a) -> StreamK m a
bracketIO bef aft bet =
concatEffect $ do
(r, ref) <- liftIO $ mask_ $ do
r <- bef
ref <- newIOFinalizer (aft r)
return (r, ref)
return $ go ref (bet r)
where
go ref m1 = mkStream $ \st yld sng stp ->
let
-- We can discard exceptions on continuations to make it equivalent
-- to StreamD, but it seems like a desirable behavior.
stop = liftIO (runIOFinalizer ref) >> stp
single a = liftIO (runIOFinalizer ref) >> sng a
yieldk a r = yld a $ go ref r
in do
-- Do not call the finalizer twice if it has already been
-- called via stop continuation and stop continuation itself
-- generated an exception. runIOFinalizer takes care of that.
res <- MC.try (foldStream (adaptState st) yieldk single stop m1)
case res of
Right r -> return r
Left (e :: MC.SomeException) ->
liftIO (runIOFinalizer ref) >> MC.throwM e
------------------------------------------------------------------------------
-- Serial Zipping
------------------------------------------------------------------------------
-- | Zipping of @n@ streams can be performed by combining the streams pair
-- wise using 'mergeMapWith' with O(n * log n) time complexity. If used
-- with 'concatMapWith' it will have O(n^2) performance.
{-# INLINE zipWith #-}
zipWith :: Monad m => (a -> b -> c) -> StreamK m a -> StreamK m b -> StreamK m c
zipWith f = zipWithM (\a b -> return (f a b))
{-# INLINE zipWithM #-}
zipWithM :: Monad m =>
(a -> b -> m c) -> StreamK m a -> StreamK m b -> StreamK m c
zipWithM f = go
where
go mx my = mkStream $ \st yld sng stp -> do
let merge a ra =
let single2 b = f a b >>= sng
yield2 b rb = f a b >>= \x -> yld x (go ra rb)
in foldStream (adaptState st) yield2 single2 stp my
let single1 a = merge a nil
yield1 = merge
foldStream (adaptState st) yield1 single1 stp mx
------------------------------------------------------------------------------
-- Merging
------------------------------------------------------------------------------
{-# INLINE mergeByM #-}
mergeByM :: Monad m =>
(a -> a -> m Ordering) -> StreamK m a -> StreamK m a -> StreamK m a
mergeByM cmp = go
where
go mx my = mkStream $ \st yld sng stp -> do
let stop = foldStream st yld sng stp my
single x = foldStream st yld sng stp (goX0 x my)
yield x rx = foldStream st yld sng stp (goX x rx my)
foldStream st yield single stop mx
goX0 x my = mkStream $ \st yld sng _ -> do
let stop = sng x
single y = do
r <- cmp x y
case r of
GT -> yld y (fromPure x)
_ -> yld x (fromPure y)
yield y ry = do
r <- cmp x y
case r of
GT -> yld y (goX0 x ry)
_ -> yld x (y `cons` ry)
in foldStream st yield single stop my