-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathPrelude.hs
More file actions
3134 lines (2561 loc) · 91.3 KB
/
Prelude.hs
File metadata and controls
3134 lines (2561 loc) · 91.3 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
{-| The names exported by this module are closely modeled on those in @Prelude@ and @Data.List@,
but also on
<http://hackage.haskell.org/package/pipes-4.1.9/docs/Pipes-Prelude.html Pipes.Prelude>,
<http://hackage.haskell.org/package/pipes-group-1.0.3/docs/Pipes-Group.html Pipes.Group>
and <http://hackage.haskell.org/package/pipes-parse-3.0.6/docs/Pipes-Parse.html Pipes.Parse>.
The module may be said to give independent expression to the conception of
Producer \/ Source \/ Generator manipulation
articulated in the latter two modules. Because we dispense with piping and
conduiting, the distinction between all of these modules collapses. Some things are
lost but much is gained: on the one hand, everything comes much closer to ordinary
beginning Haskell programming and, on the other, acquires the plasticity of programming
directly with a general free monad type. The leading type, @Stream (Of a) m r@ is chosen to permit an api
that is as close as possible to that of @Data.List@ and the @Prelude@.
Import qualified thus:
> import Streaming
> import qualified Streaming.Prelude as S
For the examples below, one sometimes needs
> import Streaming.Prelude (each, yield, next, mapped, stdoutLn, stdinLn)
> import Data.Function ((&))
Other libraries that come up in passing are
> import qualified Control.Foldl as L -- cabal install foldl
> import qualified Pipes as P
> import qualified Pipes.Prelude as P
> import qualified System.IO as IO
Here are some correspondences between the types employed here and elsewhere:
> streaming | pipes | conduit | io-streams
> -------------------------------------------------------------------------------------------------------------------
> Stream (Of a) m () | Producer a m () | Source m a | InputStream a
> | ListT m a | ConduitM () o m () | Generator r ()
> -------------------------------------------------------------------------------------------------------------------
> Stream (Of a) m r | Producer a m r | ConduitM () o m r | Generator a r
> -------------------------------------------------------------------------------------------------------------------
> Stream (Of a) m (Stream (Of a) m r) | Producer a m (Producer a m r) |
> --------------------------------------------------------------------------------------------------------------------
> Stream (Stream (Of a) m) r | FreeT (Producer a m) m r |
> --------------------------------------------------------------------------------------------------------------------
> --------------------------------------------------------------------------------------------------------------------
> ByteString m () | Producer ByteString m () | Source m ByteString | InputStream ByteString
> --------------------------------------------------------------------------------------------------------------------
>
-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Streaming.Prelude (
-- * Types
Of (..)
-- * Introducing streams of elements
-- $producers
, yield
, each
, stdinLn
, readLn
, fromHandle
, readFile
, iterate
, iterateM
, repeat
, repeatM
, replicate
, untilLeft
, untilRight
, cycle
, replicateM
, enumFrom
, enumFromThen
, unfoldr
-- * Consuming streams of elements
-- $consumers
, stdoutLn
, stdoutLn'
, mapM_
, print
, toHandle
, writeFile
, effects
, erase
, drained
-- * Stream transformers
-- $pipes
, map
, mapM
, maps
, mapsPost
, mapped
, mappedPost
, for
, with
, subst
, copy
, duplicate
, store
, chain
, sequence
, nubOrd
, nubOrdOn
, nubInt
, nubIntOn
, filter
, filterM
, mapMaybeM
, delay
, intersperse
, take
, takeWhile
-- , takeWhile'
, takeWhileM
, drop
, dropWhile
, concat
-- , elemIndices
-- , findIndices
, scan
, scanM
, scanned
, read
, show
, cons
, slidingWindow
, slidingWindowSum
, slidingWindowMin
, slidingWindowMinBy
, slidingWindowMinOn
, slidingWindowMax
, slidingWindowMaxBy
, slidingWindowMaxOn
, wrapEffect
-- * Splitting and inspecting streams of elements
, next
, uncons
, splitAt
, split
, breaks
, break
, breakWhen
, span
, group
, groupBy
-- , groupedBy
-- * Sum and Compose manipulation
, distinguish
, switch
, separate
, unseparate
, eitherToSum
, sumToEither
, sumToCompose
, composeToSum
-- * Folds
-- $folds
, fold
, fold_
, foldM
, foldM_
, foldMap
, foldMap_
, all
, all_
, any
, any_
, sum
, sum_
, product
, product_
, head
, head_
, last
, last_
, elem
, elem_
, notElem
, notElem_
, length
, length_
, toList
, toList_
, mconcat
, mconcat_
, minimum
, minimum_
, maximum
, maximum_
, foldrM
, foldrT
-- , all
-- , any
-- , and
-- , or
-- , elem
-- , find
-- , findIndex
-- , head
-- , index
-- , last
-- , length
-- , maximum
-- , minimum
-- , null
-- * Zips and unzips
, zip
, zipWith
, zip3
, zipWith3
, unzip
, partitionEithers
, partition
-- * Merging streams
-- $merging
, merge
, mergeOn
, mergeBy
-- * Maybes
-- $maybes
, catMaybes
, mapMaybe
-- * Pair manipulation
, lazily
, strictly
, fst'
, snd'
, mapOf
, _first
, _second
-- * Interoperation
, reread
-- * Basic Type
, Stream
) where
import Streaming.Internal
import Control.Applicative (Applicative (..))
import Control.Concurrent (threadDelay)
import Control.Exception (throwIO, try)
import Control.Monad hiding (filterM, mapM, mapM_, foldM, foldM_, replicateM, sequence)
import Control.Monad.Trans
import Data.Functor (Functor (..), (<$))
import Data.Functor.Compose
import Data.Functor.Identity
import Data.Functor.Of
import Data.Functor.Sum
import Data.Monoid (Monoid (mappend, mempty))
import Data.Ord (Ordering (..), comparing)
import Data.Semigroup (Semigroup (..))
import Foreign.C.Error (Errno(Errno), ePIPE)
import Text.Read (readMaybe)
import qualified Data.AnnotatedQueue as AQ
import qualified Data.Foldable as Foldable
import qualified Data.IntSet as IntSet
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import Data.Word (Word64)
import qualified GHC.IO.Exception as G
import qualified Prelude
import qualified System.IO as IO
import Prelude hiding (map, mapM, mapM_, filter, drop, dropWhile, take, mconcat
, sum, product, iterate, repeat, cycle, replicate, splitAt
, takeWhile, enumFrom, enumFromTo, enumFromThen, length
, print, zipWith, zip, zipWith3, zip3, unzip, seq, show, read
, readLn, sequence, concat, span, break, readFile, writeFile
, minimum, maximum, elem, notElem, all, any, head
, last, foldMap)
-- $setup
-- >>> import Control.Applicative
-- >>> import qualified Control.Foldl as L
-- >>> import Data.Bifunctor (first)
-- >>> import Data.Function ((&))
-- >>> import Data.IORef
-- >>> import Data.Vector (Vector)
-- >>> import qualified Streaming.Prelude as S
-- >>> import qualified System.IO
-- >>> import Text.Read (readEither)
-- instance (Eq a) => Eq1 (Of a) where eq1 = (==)
-- instance (Ord a) => Ord1 (Of a) where compare1 = compare
-- instance (Read a) => Read1 (Of a) where readsPrec1 = readsPrec
-- instance (Show a) => Show1 (Of a) where showsPrec1 = showsPrec
{-| Note that 'lazily', 'strictly', 'fst'', and 'mapOf' are all so-called /natural transformations/ on the primitive @Of a@ functor.
If we write
> type f ~~> g = forall x . f x -> g x
then we can restate some types as follows:
> mapOf :: (a -> b) -> Of a ~~> Of b -- Bifunctor first
> lazily :: Of a ~~> (,) a
> Identity . fst' :: Of a ~~> Identity a
Manipulation of a @Stream f m r@ by mapping often turns on recognizing natural transformations of @f@.
Thus @maps@ is far more general the the @map@ of the @Streaming.Prelude@, which can be
defined thus:
> S.map :: (a -> b) -> Stream (Of a) m r -> Stream (Of b) m r
> S.map f = maps (mapOf f)
i.e.
> S.map f = maps (\(a :> x) -> (f a :> x))
This rests on recognizing that @mapOf@ is a natural transformation; note though
that it results in such a transformation as well:
> S.map :: (a -> b) -> Stream (Of a) m ~~> Stream (Of b) m
Thus we can @maps@ it in turn.
-}
lazily :: Of a b -> (a,b)
lazily = \(a:>b) -> (a,b)
{-# INLINE lazily #-}
{-| Convert a standard Haskell pair into a left-strict pair -}
strictly :: (a,b) -> Of a b
strictly = \(a,b) -> a :> b
{-# INLINE strictly #-}
{-| @fst'@ and @snd'@ extract the first and second element of a pair
>>> S.fst' (1:>"hi")
1
>>> S.snd' (1:>"hi")
"hi"
They are contained in the @_first@ and @_second@ lenses,
if any lens library is in scope
>>> import Lens.Micro
>>> (1:>"hi") ^. S._first
1
>>> (1:>"hi") ^. S._second
"hi"
-}
fst' :: Of a b -> a
fst' (a :> _) = a
{-# INLINE fst' #-}
snd' :: Of a b -> b
snd' (_ :> b) = b
{-# INLINE snd' #-}
{-| Map a function over the first element of an @Of@ pair
>>> S.mapOf even (1:>"hi")
False :> "hi"
@mapOf@ is just @first@ from the @Bifunctor@ instance
>>> first even (1:>"hi")
False :> "hi"
and is contained in the @_first@ lens
>>> import Lens.Micro
>>> over S._first even (1:>"hi")
False :> "hi"
-}
mapOf :: (a -> b) -> Of a r -> Of b r
mapOf f (a :> b) = f a :> b
{-# INLINE mapOf #-}
{-| A lens into the first element of a left-strict pair -}
_first :: Functor f => (a -> f a') -> Of a b -> f (Of a' b)
_first afb (a :> b) = fmap (\c -> c :> b) (afb a)
{-# INLINE _first #-}
{-| A lens into the second element of a left-strict pair -}
_second :: Functor f => (b -> f b') -> Of a b -> f (Of a b')
_second afb (a :> b) = fmap (\c -> a :> c) (afb b)
{-# INLINABLE _second #-}
all :: Monad m => (a -> Bool) -> Stream (Of a) m r -> m (Of Bool r)
all thus = loop True where
loop b str = case str of
Return r -> return (b :> r)
Effect m -> m >>= loop b
Step (a :> rest) -> if thus a
then loop True rest
else do
r <- effects rest
return (False :> r)
{-# INLINABLE all #-}
all_ :: Monad m => (a -> Bool) -> Stream (Of a) m r -> m Bool
all_ thus = loop True where
loop b str = case str of
Return _ -> return b
Effect m -> m >>= loop b
Step (a :> rest) -> if thus a
then loop True rest
else return False
{-# INLINABLE all_ #-}
any :: Monad m => (a -> Bool) -> Stream (Of a) m r -> m (Of Bool r)
any thus = loop False where
loop b str = case str of
Return r -> return (b :> r)
Effect m -> m >>= loop b
Step (a :> rest) -> if thus a
then do
r <- effects rest
return (True :> r)
else loop False rest
{-# INLINABLE any #-}
any_ :: Monad m => (a -> Bool) -> Stream (Of a) m r -> m Bool
any_ thus = loop False where
loop b str = case str of
Return _ -> return b
Effect m -> m >>= loop b
Step (a :> rest) -> if thus a
then return True
else loop False rest
{-# INLINABLE any_ #-}
{-| Break a sequence upon meeting element falls under a predicate,
keeping it and the rest of the stream as the return value.
>>> rest <- S.print $ S.break even $ each [1,1,2,3]
1
1
>>> S.print rest
2
3
-}
break :: Monad m => (a -> Bool) -> Stream (Of a) m r
-> Stream (Of a) m (Stream (Of a) m r)
break thePred = loop where
loop str = case str of
Return r -> Return (Return r)
Effect m -> Effect $ fmap loop m
Step (a :> rest) -> if thePred a
then Return (Step (a :> rest))
else Step (a :> loop rest)
{-# INLINABLE break #-}
{-| Yield elements, using a fold to maintain state, until the accumulated
value satifies the supplied predicate. The fold will then be short-circuited
and the element that breaks it will be put after the break.
This function is easiest to use with 'Control.Foldl.purely'
>>> rest <- each [1..10] & L.purely S.breakWhen L.sum (>10) & S.print
1
2
3
4
>>> S.print rest
5
6
7
8
9
10
-}
breakWhen :: Monad m => (x -> a -> x) -> x -> (x -> b) -> (b -> Bool) -> Stream (Of a) m r -> Stream (Of a) m (Stream (Of a) m r)
breakWhen step begin done thePred = loop0 begin
where
loop0 x stream = case stream of
Return r -> return (return r)
Effect mn -> Effect $ fmap (loop0 x) mn
Step (a :> rest) -> loop a (step x a) rest
loop a !x stream =
if thePred (done x)
then return (yield a >> stream)
else case stream of
Return r -> yield a >> return (return r)
Effect mn -> Effect $ fmap (loop a x) mn
Step (a' :> rest) -> do
yield a
loop a' (step x a') rest
{-# INLINABLE breakWhen #-}
{-| Break during periods where the predicate is not satisfied, grouping the periods when it is.
>>> S.print $ mapped S.toList $ S.breaks not $ S.each [False,True,True,False,True,True,False]
[True,True]
[True,True]
>>> S.print $ mapped S.toList $ S.breaks id $ S.each [False,True,True,False,True,True,False]
[False]
[False]
[False]
-}
breaks
:: Monad m =>
(a -> Bool) -> Stream (Of a) m r -> Stream (Stream (Of a) m) m r
breaks thus = loop where
loop stream = Effect $ do
e <- next stream
return $ case e of
Left r -> Return r
Right (a, p') ->
if not (thus a)
then Step $ fmap loop (yield a >> break thus p')
else loop p'
{-# INLINABLE breaks #-}
{-| Apply an action to all values, re-yielding each.
The return value (@y@) of the function is ignored.
>>> S.product $ S.chain Prelude.print $ S.each [1..5]
1
2
3
4
5
120 :> ()
See also 'mapM' for a variant of this which uses the return value of the function to transorm the values in the stream.
-}
chain :: Monad m => (a -> m y) -> Stream (Of a) m r -> Stream (Of a) m r
chain f = loop where
loop str = case str of
Return r -> return r
Effect mn -> Effect (fmap loop mn)
Step (a :> rest) -> Effect $ do
_ <- f a
return (Step (a :> loop rest))
{-# INLINABLE chain #-}
{-| Make a stream of foldable containers into a stream of their separate elements.
This is just
> concat str = for str each
>>> S.print $ S.concat (each ["xy","z"])
'x'
'y'
'z'
Note that it also has the effect of 'Data.Maybe.catMaybes', 'Data.Either.rights'
@map snd@ and such-like operations.
>>> S.print $ S.concat $ S.each [Just 1, Nothing, Just 2]
1
2
>>> S.print $ S.concat $ S.each [Right 1, Left "Error!", Right 2]
1
2
>>> S.print $ S.concat $ S.each [('A',1), ('B',2)]
1
2
-}
concat :: (Monad m, Foldable.Foldable f) => Stream (Of (f a)) m r -> Stream (Of a) m r
concat = loop
where
loop str = case str of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step (lst :> as) ->
let inner [] = loop as
inner (x:rest) = Step (x :> inner rest)
in inner (Foldable.toList lst)
{-# INLINABLE concat #-}
-- The above hand-written loop is ~20% faster than the 'for' implementation
-- concat str = for str each
{-| The natural @cons@ for a @Stream (Of a)@.
> cons a stream = yield a >> stream
Useful for interoperation:
> Data.Text.foldr S.cons (return ()) :: Text -> Stream (Of Char) m ()
> Lazy.foldrChunks S.cons (return ()) :: Lazy.ByteString -> Stream (Of Strict.ByteString) m ()
and so on.
-}
cons :: (Monad m) => a -> Stream (Of a) m r -> Stream (Of a) m r
cons a str = Step (a :> str)
{-# INLINE cons #-}
{- | Cycle repeatedly through the layers of a stream, /ad inf./ This
function is functor-general
> cycle = forever
>>> rest <- S.print $ S.splitAt 3 $ S.cycle (yield True >> yield False)
True
False
True
>>> S.print $ S.take 3 rest
False
True
False
-}
cycle :: (Monad m, Functor f) => Stream f m r -> Stream f m s
cycle str = loop where loop = str >> loop
{-# INLINABLE cycle #-}
{-| Interpolate a delay of n seconds between yields.
-}
delay :: MonadIO m => Double -> Stream (Of a) m r -> Stream (Of a) m r
delay seconds = loop where
pico = truncate (seconds * 1000000)
loop str = do
e <- lift $ next str
case e of
Left r -> Return r
Right (a,rest) -> do
yield a
liftIO $ threadDelay pico
loop rest
{-# INLINABLE delay #-}
{-| Where a transformer returns a stream, run the effects of the stream, keeping
the return value. This is usually used at the type
> drained :: Monad m => Stream (Of a) m (Stream (Of b) m r) -> Stream (Of a) m r
> drained = join . fmap (lift . effects)
Here, for example, we split a stream in two places and throw out the middle segment:
>>> rest <- S.print $ S.drained $ S.splitAt 2 $ S.splitAt 5 $ each [1..7]
1
2
>>> S.print rest
6
7
In particular, we can define versions of @take@ and @takeWhile@ which
retrieve the return value of the rest of the stream - and which can
thus be used with 'maps':
> take' n = S.drained . S.splitAt n
> takeWhile' thus = S.drained . S.span thus
-}
drained :: (Monad m, Monad (t m), MonadTrans t) => t m (Stream (Of a) m r) -> t m r
drained tms = tms >>= lift . effects
{-# INLINE drained #-}
-- ---------------
-- drop
-- ---------------
{-| Ignore the first n elements of a stream, but carry out the actions
>>> S.toList $ S.drop 2 $ S.replicateM 5 getLine
a<Enter>
b<Enter>
c<Enter>
d<Enter>
e<Enter>
["c","d","e"] :> ()
Because it retains the final return value, @drop n@ is a suitable argument
for @maps@:
>>> S.toList $ concats $ maps (S.drop 4) $ chunksOf 5 $ each [1..20]
[5,10,15,20] :> ()
-}
drop :: (Monad m) => Int -> Stream (Of a) m r -> Stream (Of a) m r
drop n str | n <= 0 = str
drop n str = loop n str where
loop 0 stream = stream
loop m stream = case stream of
Return r -> Return r
Effect ma -> Effect (fmap (loop m) ma)
Step (_ :> as) -> loop (m-1) as
{-# INLINABLE drop #-}
-- ---------------
-- dropWhile
-- ---------------
{- | Ignore elements of a stream until a test succeeds, retaining the rest.
>>> S.print $ S.dropWhile ((< 5) . length) S.stdinLn
one<Enter>
two<Enter>
three<Enter>
"three"
four<Enter>
"four"
^CInterrupted.
-}
dropWhile :: Monad m => (a -> Bool) -> Stream (Of a) m r -> Stream (Of a) m r
dropWhile thePred = loop where
loop stream = case stream of
Return r -> Return r
Effect ma -> Effect (fmap loop ma)
Step (a :> as) -> if thePred a
then loop as
else Step (a :> as)
{-# INLINABLE dropWhile #-}
-- ---------------
-- each
-- ---------------
{- | Stream the elements of a pure, foldable container.
>>> S.print $ each [1..3]
1
2
3
-}
each :: (Monad m, Foldable.Foldable f) => f a -> Stream (Of a) m ()
each = Foldable.foldr (\a p -> Step (a :> p)) (Return ())
{-# INLINABLE each #-}
-- ---------------
-- effects
-- ---------------
{- | Reduce a stream, performing its actions but ignoring its elements.
>>> rest <- S.effects $ S.splitAt 2 $ each [1..5]
>>> S.print rest
3
4
5
'effects' should be understood together with 'copy' and is subject to the rules
> S.effects . S.copy = id
> hoist S.effects . S.copy = id
The similar @effects@ and @copy@ operations in @Data.ByteString.Streaming@ obey the same rules.
-}
effects :: Monad m => Stream (Of a) m r -> m r
effects = loop where
loop stream = case stream of
Return r -> return r
Effect m -> m >>= loop
Step (_ :> rest) -> loop rest
{-# INLINABLE effects #-}
{-| Before evaluating the monadic action returning the next step in the 'Stream', @wrapEffect@
extracts the value in a monadic computation @m a@ and passes it to a computation @a -> m y@.
-}
wrapEffect :: (Monad m, Functor f) => m a -> (a -> m y) -> Stream f m r -> Stream f m r
wrapEffect m f = loop where
loop stream = do
x <- lift m
step <- lift $ inspect stream
_ <- lift $ f x
either pure loop' step
loop' stream = wrap (fmap loop stream)
{-| Exhaust a stream remembering only whether @a@ was an element.
-}
elem :: (Monad m, Eq a) => a -> Stream (Of a) m r -> m (Of Bool r)
elem a' = loop False where
loop True str = fmap (True :>) (effects str)
loop False str = case str of
Return r -> return (False :> r)
Effect m -> m >>= loop False
Step (a:> rest) ->
if a == a'
then fmap (True :>) (effects rest)
else loop False rest
{-# INLINABLE elem #-}
elem_ :: (Monad m, Eq a) => a -> Stream (Of a) m r -> m Bool
elem_ a' = loop False where
loop True _ = return True
loop False str = case str of
Return _ -> return False
Effect m -> m >>= loop False
Step (a:> rest) ->
if a == a'
then return True
else loop False rest
{-# INLINABLE elem_ #-}
-- -----
-- enumFrom
-- ------
{-| An infinite stream of enumerable values, starting from a given value.
It is the same as @S.iterate succ@.
Because their return type is polymorphic, @enumFrom@, @enumFromThen@
and @iterate@ are useful with functions like @zip@ and @zipWith@, which
require the zipped streams to have the same return type.
For example, with
@each [1..]@ the following bit of connect-and-resume would not compile:
>>> rest <- S.print $ S.zip (S.enumFrom 1) $ S.splitAt 3 $ S.each ['a'..'z']
(1,'a')
(2,'b')
(3,'c')
>>> S.print $ S.take 3 rest
'd'
'e'
'f'
-}
enumFrom :: (Monad m, Enum n) => n -> Stream (Of n) m r
enumFrom = loop where
loop !n = Effect (return (Step (n :> loop (succ n))))
{-# INLINABLE enumFrom #-}
{-| An infinite sequence of enumerable values at a fixed distance, determined
by the first and second values. See the discussion of 'Streaming.enumFrom'
>>> S.print $ S.take 3 $ S.enumFromThen 100 200
100
200
300
-}
enumFromThen:: (Monad m, Enum a) => a -> a -> Stream (Of a) m r
enumFromThen first second = Streaming.Prelude.map toEnum (loop _first)
where
_first = fromEnum first
_second = fromEnum second
diff = _second - _first
loop !s = Step (s :> loop (s+diff))
{-# INLINABLE enumFromThen #-}
-- ---------------
-- erase
-- ---------------
{- | Remove the elements from a stream of values, retaining the structure of layers.
-}
erase :: Monad m => Stream (Of a) m r -> Stream Identity m r
erase = loop where
loop str = case str of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step (_:>rest) -> Step (Identity (loop rest))
{-# INLINABLE erase #-}
-- ---------------
-- filter
-- ---------------
-- | Skip elements of a stream that fail a predicate
filter :: (Monad m) => (a -> Bool) -> Stream (Of a) m r -> Stream (Of a) m r
filter thePred = loop where
loop str = case str of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step (a :> as) -> if thePred a
then Step (a :> loop as)
else loop as
{-# INLINE filter #-} -- ~ 10% faster than INLINABLE in simple bench
-- ---------------
-- filterM
-- ---------------
-- | Skip elements of a stream that fail a monadic test
filterM :: (Monad m) => (a -> m Bool) -> Stream (Of a) m r -> Stream (Of a) m r
filterM thePred = loop where
loop str = case str of
Return r -> Return r
Effect m -> Effect $ fmap loop m
Step (a :> as) -> Effect $ do
bool <- thePred a
if bool
then return $ Step (a :> loop as)
else return $ loop as
{-# INLINE filterM #-} -- ~ 10% faster than INLINABLE in simple bench
-- -- ---------------
-- -- first
-- -- ---------------
-- {- | Take either the first item in a stream or the return value, if it is empty.
-- The typical mark of an infinite stream is a polymorphic return value; in
-- that case, 'first' is a sort of @safeHead@
--
-- To iterate an action returning a 'Maybe', until it succeeds.
--
-- -}
-- first :: Monad m => Stream (Of r) m r -> m r
-- first = loop where
-- loop str = case str of
-- Return r -> return r
-- Effect m -> m >>= loop
-- Step (r :> rest) -> return r
-- {-# INLINABLE first #-}
-- ---------------
-- fold
-- ---------------
{- $folds
Use these to fold the elements of a 'Stream'.
>>> S.fold_ (+) 0 id $ S.each [1..10]
55
The general folds 'fold', 'fold_', 'foldM' and 'foldM_' are arranged
for use with @Control.Foldl@ 'Control.Foldl.purely' and 'Control.Foldl.impurely'
>>> L.purely fold_ L.sum $ each [1..10]
55
>>> L.purely fold_ (liftA3 (,,) L.sum L.product L.list) $ each [1..10]
(55,3628800,[1,2,3,4,5,6,7,8,9,10])
All functions marked with an underscore
(e.g. @fold_@, @sum_@) omit the stream's return value in a left-strict pair.
They are good for exiting streaming completely,
but when you are, e.g. @mapped@-ing over a @Stream (Stream (Of a) m) m r@,
which is to be compared with @[[a]]@. Specializing, we have e.g.
> mapped sum :: (Monad m, Num n) => Stream (Stream (Of Int)) IO () -> Stream (Of n) IO ()
> mapped (fold mappend mempty id) :: Stream (Stream (Of Int)) IO () -> Stream (Of Int) IO ()
>>> S.print $ mapped S.sum $ chunksOf 3 $ S.each [1..10]
6
15
24
10
>>> let three_folds = L.purely S.fold (liftA3 (,,) L.sum L.product L.list)
>>> S.print $ mapped three_folds $ chunksOf 3 (each [1..10])
(6,6,[1,2,3])
(15,120,[4,5,6])
(24,504,[7,8,9])
(10,10,[10])
-}
{-| Strict fold of a 'Stream' of elements, preserving only the result of the fold, not
the return value of the stream. The third parameter will often be 'id' where a fold
is written by hand:
>>> S.fold_ (+) 0 id $ each [1..10]
55
It can be used to replace a standard Haskell type with one more suited to
writing a strict accumulation function. It is also crucial to the
Applicative instance for @Control.Foldl.Fold@
> Control.Foldl.purely fold :: Monad m => Fold a b -> Stream (Of a) m () -> m b
-}
fold_ :: Monad m => (x -> a -> x) -> x -> (x -> b) -> Stream (Of a) m r -> m b
fold_ step begin done = fmap (\(a :> _) -> a) . fold step begin done
{-# INLINE fold_ #-}