úÎãØS«      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ªNone *+357IN6Map a stream directly to its church encoding; compare Data.List.foldr reorders the arguments of  to be more akin to foldre It is more convenient to query in ghci to figure out what kind of 'algebra' you need to write. :t streamFold return join(Monad m, Functor f) => < (f (m a) -> m a) -> Stream f m a -> m a -- iterT":t streamFold return (join . lift)2(Monad m, Monad (t m), Functor f, MonadTrans t) =>= (f (t m a) -> t m a) -> Stream f m a -> t m a -- iterTM:t streamFold return effect"(Monad m, Functor f, Functor g) =>G (f (Stream g m r) -> Stream g m r) -> Stream f m r -> Stream g m r,:t \f -> streamFold return effect (wrap . f)"(Monad m, Functor f, Functor g) =>+ (f (Stream g m a) -> g (Stream g m a))< -> Stream f m a -> Stream g m a -- maps;:t \f -> streamFold return effect (effect . liftM wrap . f)"(Monad m, Functor f, Functor g) =>/ (f (Stream g m a) -> m (g (Stream g m a)))> -> Stream f m a -> Stream g m a -- mapped$So for example, when we realize that:t streamFold return Q.mwrap(Monad m, Functor f) =>- (f (Q.ByteString m a) -> Q.ByteString m a)& -> Stream f m a -> Q.ByteString m ait is easy to see how to write  fromChunks:6streamFold return Q.mwrap (\(a:>b) -> Q.chunk a >> b)IMonad m => Stream (Of B.ByteString) m a -> Q.ByteString m a -- fromChunks%Reflect a church-encoded stream; cp. GHC.Exts.build #destroy a b c (streamBuild psi) = CInspect the first stage of a freely layered sequence. Compare  Pipes.next and the replica Streaming.Prelude.next. This is the uncons for the general  . Hunfold inspect = id Streaming.Prelude.unfoldr StreamingPrelude.next = id Build a StreamG by unfolding steps starting from a seed. See also the specialized  in the prelude. Ïunfold inspect = id -- modulo the quotient we work with unfold Pipes.next :: Monad m => Producer a m r -> Stream ((,) a) m r unfold (curry (:>) . Pipes.next) :: Monad m => Producer a m r -> Stream (Of a) m r!rMap layers of one functor to another with a transformation. Compare hoist, which has a similar effect on the monadic parameter. +maps id = id maps f . maps g = maps (f . g)"YMap layers of one functor to another with a transformation involving the base monad maps is more fundamental than mapsMY, which is best understood as a convenience for effecting this frequent composition: ,mapsM phi = decompose . maps (Compose . phi)#YMap layers of one functor to another with a transformation involving the base monad maps is more fundamental than mappedY, which is best understood as a convenience for effecting this frequent composition: >mapped = mapsM mapsM phi = decompose . maps (Compose . phi) mapped obeys these rules: mapped return = id mapped f . mapped g = mapped (f <=< g) map f . mapped g = mapped (liftM f . g) mapped f . map g = mapped (f . g)$*Resort a succession of layers of the form m (f x) . Though mapsM is best understood as: ,mapsM phi = decompose . maps (Compose . phi)we could as well define  decompose by mapsM: decompose = mapsM getCompose%7Run the effects in a stream that merely layers effects.&.Map each layer to an effect, and run them all.'=Interpolate a layer at each segment. This specializes to e.g. `intercalates :: (Monad m, Functor f) => Stream f m () -> Stream (Stream f m) m r -> Stream f m r((Specialized fold following the usage of Control.Monad.Trans.Free ,iterTM alg = streamFold return (join . lift))(Specialized fold following the usage of Control.Monad.Trans.Free 'iterT alg = streamFold return join alg **Dissolves the segmentation into layers of  Stream f m layers.+\Split a succession of layers after some number, returning a streaming or effectful pair.+rest <- S.print $ S.splitAt 1 $ each [1..3]1 S.print rest23 :splitAt 0 = return splitAt n >=> splitAt m = splitAt (m+n) Thus, e.g. 9rest <- S.print $ splitsAt 2 >=> splitsAt 2 $ each [1..5]1234 S.print rest5->Break a stream into substreams each with n functorial layers. 6S.print $ mapped S.sum $ chunksOf 2 $ each [1,1,1,1,1]221.<Make it possible to 'run' the underlying transformed monad. /:Repeat a functorial layer, command or instruction forever.1=Repeat a functorial layer, command or instruct several times.24Construct an infinite stream by cycling a finite one cycles = forever7This is akin to the observe of Pipes.Internal1 . It reeffects the layering in instances of  Stream f m r$ so that it replicates that of FreeT. :vLift for items in the base functor. Makes a singleton or one-layer succession. It is named by similarity to lift: nlift :: (Monad m, Functor f) => m r -> Stream f m r yields :: (Monad m, Functor f) => f r -> Stream f m r=aInterleave functor layers, with the effects of the first preceding the effects of the second. #interleaves = zipsWith (liftA2 (,))Mlet paste = \a b -> interleaves (Q.lines a) (maps (Q.cons' '\t') (Q.lines b))@Q.stdout $ Q.unlines $ paste "hello\nworld\n" "goodbye\nworld\n" hello goodbye world world>1Swap the order of functors in a sum of functors. `S.toListM' $ S.print $ separate $ maps S.switch $ maps (S.distinguish (=='a')) $ S.each "banana"'a''a''a' "bnn" :> ()PS.toListM' $ S.print $ separate $ maps (S.distinguish (=='a')) $ S.each "banana"'b''n''n' "aaa" :> ()?ÕGiven a stream on a sum of functors, make it a stream on the left functor, with the streaming on the other functor as the governing monad. This is useful for acting on one or the other functor with a fold.@let odd_even = S.maps (S.distinguish even) $ S.each [1..10::Int]:t separate odd_evenseparate odd_even6 :: Monad m => Stream (Of Int) (Stream (Of Int) m) ()SNow, for example, it is convenient to fold on the left and right values separately:#toList $ toList $ separate odd_even#[2,4,6,8,10] :> ([1,3,5,7,9] :> ())>We can achieve the above effect more simply in the case of Stream (Of a) m r by using TS.toList . S.filter even $ S.toList . S.filter odd $ S.duplicate $ each [1..10::Int]#[2,4,6,8,10] :> ([1,3,5,7,9] :> ())But ? and @ are functor-general. B]Group layers in an alternating stream into adjoining sub-streams of one type or another. 8« !"#$%&'()*+,-./0123456789:;<=>?@AB¬­®¯°±²³Žµ¶, !"#$%&'()*+,-./0123456789:;<=>?@AB, 1/089:2'*)(!"#$&%.B-+,;<A=?@>734565« !"#$%&'()*+,-./0123456789:;<=>?@AB¬­®¯°±²³Žµ¶None +-./>ILNOCHA left-strict pair; the base functor for streams of individual elements.E Note that E, F, G, and · 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 lmap lazily :: Of a ~~> (,) a Identity . fst' :: Of a ~~> Identity aManipulation of a  Stream f m rB by mapping often turns on recognizing natural transformations of f , thus maps is far more general the the map5 of the present module, which can be defined thus: V S.map :: (a -> b) -> Stream (Of a) m r -> Stream (Of b) m r S.map f = maps (mapOf f)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 M~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]11 S.print rest23Nÿÿ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 Arest <- each [1..10] & L.purely S.breakWhen L.sum (>10) & S.print1234 S.print rest5678910O/Apply an action to all values, re-yielding each1S.product $ S.chain Prelude.print $ S.each [1..5]12345 120 :> ()PcMake a stream of traversable containers into a stream of their separate elements. This is just  concat = for str each$S.print $ S.concat (each ["xy","z"])'x''y''z'$Note that it also has the effect of  ,  ( 'map snd' and such-like operations.5S.print $ S.concat $ S.each [Just 1, Nothing, Just 2]12>S.print $ S.concat $ S.each [Right 1, Left "Error!", Right 2]12.S.print $ S.concat $ S.each [('A',1), ('B',2)]12Q The natural cons for a  Stream (Of a).  !cons a stream = yield a >> streamUseful 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.R1Cycle 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 0 >> yield 1)TrueFalseTrueS.print $ S.take 3 restFalseTrueFalseSATCReduce a stream, performing its actions but ignoring its elements. -rest <- S.effects $ S.splitAt 2 $ each [1..5] S.print rest345U‚Where a transformer returns a stream, run the effects of the stream, keeping the return value. This is usually used at the type udrained :: Monad m => Stream (Of a) m (Stream (Of b) m r) -> Stream (Of a) m r drained = join . fmap (lift . effects)THere, for example, we split a stream in two places and throw out the middle segment:Erest <- S.print $ S.drained $ S.splitAt 2 $ S.splitAt 5 $ each [1..7]12 S.print rest67*In particular, we can define versions of take and  takeWhilee which retrieve the return value of the rest of the stream - and which can thus be used with !: Ktake' n = S.drained . S.splitAt n takeWhile' thus = S.drained . S.span thusVBIgnore the first n elements of a stream, but carry out the actions-S.toList $ S.drop 2 $ S.replicateM 5 getLinea<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] :> ()WFIgnore elements of a stream until a test succeeds, retaining the rest.0S.print $ S.dropWhile ((< 5) . length) S.stdinLn one<Enter> two<Enter> three<Enter>"three" four<Enter>"four"^CInterrupted.X2Stream the elements of a pure, foldable container.each [1..3] & S.print123?S.replicateM 5 getLine & chunksOf 3 & mapped S.toList & S.printstu ["s","t","u"]vw ["v","w"]Y*Exhaust a stream remembering only whether a was an element.[œ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 and  enumFromThen (and iterate are useful for example with zip and zipWithE, which require the same return type in the zipped streams. With  each [1..]= the following bit of connect-and-resume would be impossible:Frest <- S.print $ S.zip (S.enumFrom 'a') $ S.splitAt 3 $ S.enumFrom 1('a',1)('b',2)('c',3)S.print $ S.take 3 rest456\ƒAn infinite sequence of enumerable values at a fixed distance, determined by the first and second values. See the discussion of  +S.print $ S.take 3 $ S.enumFromThen 100 200100200300]/Skip elements of a stream that fail a predicate^2Skip elements of a stream that fail a monadic test_Strict fold of a  of elements, preserving only the result of the fold, not the return value of the stream. The third parameter will often be ž% 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 MControl.Foldl.purely fold :: Monad m => Fold a b -> Stream (Of a) m () -> m b`Strict fold of a U of elements that preserves the return value. The third parameter will often be ž! where a fold is written by hand:S.fold (+) 0 id $ each [1..10]55 :> ()>S.fold (*) 1 id $ S.fold (+) 0 id $ S.duplicate $ each [1..10]3628800 :> (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 We can apply such a fold purely UControl.Foldl.purely S.fold :: Monad m => Fold a b -> Stream (Of a) m r -> m (Of b r)Thus, specializing a bit: ”L.purely S.fold L.sum :: Stream (Of Int) Int r -> m (Of Int r) maps (L.purely S.fold L.sum) :: Stream (Stream (Of Int)) IO r -> Stream (Of Int) IO r)Here we use the Applicative instance for Control.Foldl.FoldV to stream three-item segments of a stream together with their sums and products.cS.print $ mapped (L.purely S.fold (liftA3 (,,) L.list L.product L.sum)) $ chunksOf 3 $ each [1..10] ([1,2,3],6,6)([4,5,6],120,15)([7,8,9],504,24) ([10],10,10)a9Strict, monadic fold of the elements of a 'Stream (Of a)' QControl.Foldl.impurely foldM :: Monad m => FoldM a b -> Stream (Of a) m () -> m bb9Strict, monadic fold of the elements of a 'Stream (Of a)' VControl.Foldl.impurely foldM' :: Monad m => FoldM a b -> Stream (Of a) m r -> m (b, r)jThus to accumulate the elements of a stream as a vector, together with a random element we might write:lL.impurely S.foldM (liftA2 (,) L.vector L.random) $ each [1..10::Int] :: IO (Of (U.Vector Int,Maybe Int) ())%([1,2,3,4,5,6,7,8,9,10],Just 9) :> ()cXA natural right fold for consuming a stream of elements. See also the more general ( in the  Streaming( module and the still more general  ¬foldrT (\a p -> Pipes.yield a >> p) :: Monad m => Stream (Of a) m r -> Producer a m r foldrT (\a p -> Conduit.yield a >> p) :: Monad m => Stream (Of a) m r -> Conduit a m rdWA natural right fold for consuming a stream of elements. See also the more general ) in the  Streaming' module and the still more general eforv replaces each element of a stream with an associated stream. Note that the associated stream may layer any functor. fGGroup elements of a stream in accordance with the supplied comparison. QS.print $ mapped S.toList $ S.groupBy (>=) $ each [1,2,3,1,2,3,4,3,2,4,5,6,7,6,5][1][2] [3,1,2,3] [4,3,2,4][5][6][7,6,5]g%Group successive equal items together5S.toList $ mapped S.toList $ S.group $ each "baaaaad"["b","aaaaa","d"] :> ()PS.toList $ concats $ maps (S.drained . S.splitAt 1) $ S.group $ each "baaaaaaad" "bad" :> ()kHIterate a pure function from a seed value, streaming the results forever¹KIterate a monadic function from a seed value, streaming the results forevern*Run a stream, remembering only its length:S.length $ S.each [1..10]10o7Run a stream, keeping its length and its return value. 7S.print $ mapped S.length $ chunksOf 3 $ S.each [1..10]3331p)Standard map on the elements of a stream.6S.stdoutLn $ S.map reverse $ each (words "alpha beta")ahplaatebqDReplace each element of a stream with the result of a monadic actioneS.print $ S.mapM readIORef $ S.chain (\ior -> modifyIORef ior (*100)) $ S.mapM newIORef $ each [1..6]100200300400500600r:Reduce a stream to its return value with a monadic action.#S.mapM_ Prelude.print $ each [1..5]12345:rest <- S.mapM_ Prelude.print $ S.splitAt 3 $ each [1..10]123 S.sum rest49 :> ()s+Fold streamed items into their monoidal sumBS.mconcat $ S.take 2 $ S.map (Data.Monoid.Last . Just) (S.stdinLn) first<Enter> last<Enter>"Last {getLast = Just "last"} :> ()yrThe standard way of inspecting the first item in a stream of elements, if the stream is still 'running'. The Right< case contains a Haskell pair, where the more general inspectE would return a left-strict pair. There is no reason to prefer inspect since, if the RightW case is exposed, the first element in the pair will have been evaluated to whnf. žnext :: Monad m => Stream (Of a) m r -> m (Either r (a, Stream (Of a) m r)) inspect :: Monad m => Stream (Of a) m r -> m (Either r (Of a (Stream (Of a) m r)))Interoperate with pipes producers thus: ‚Pipes.unfoldr Stream.next :: Stream (Of a) m r -> Producer a m r Stream.unfoldr Pipes.next :: Producer a m r -> Stream (Of a) m r  Similarly:  ÎIOStreams.unfoldM (liftM (either (const Nothing) Just) . next) :: Stream (Of a) IO b -> IO (InputStream a) Conduit.unfoldM (liftM (either (const Nothing) Just) . next) :: Stream (Of a) m r -> Source a m rBut see ’", which is better fitted to these unfoldMsz(Remove repeated elements from a Stream. z of course accumulates a  O of elements that have already been seen and should thus be used with care.3S.toList_ $ S.nub $ S.take 5 S.readLn :: IO ([Int])1<Enter>2<Enter>3<Enter>1<Enter>2<Enter>[1,2,3]{Fold a  of numbers into their product|Fold a 4 of numbers into their product with the return value F maps' product' :: Stream (Stream (Of Int)) m r -> Stream (Of Int) m r}KMake a stream of strings into a stream of parsed values, skipping bad cases>S.sum_ $ S.read $ S.takeWhile (/= "total") S.stdinLn :: IO Int 1000<Enter> 2000<Enter> total<Enter>3000~Repeat an element ad inf. .S.print $ S.take 3 $ S.repeat 1111Repeat a monadic action ad inf., streaming its results.%S.toList $ S.take 2 $ repeatM getLine one<Enter> two<Enter> ["one","two"]€Repeat an element several times6Repeat an action several times, streaming the results.'S.print $ S.replicateM 2 getCurrentTime2015-08-18 00:57:36.124508 UTC2015-08-18 00:57:36.124785 UTC‚Read an IORef (Maybe a)$ or a similar device until it reads Nothing. reread# provides convenient exit from the  io-streams library ‹reread readIORef :: IORef (Maybe a) -> Stream (Of a) IO () reread Streams.read :: System.IO.Streams.InputStream a -> Stream (Of a) IO ()ƒ=Strict left scan, streaming, e.g. successive partial results.4S.print $ S.scan (++) "" id $ each (words "a b c d")"""a""ab""abc""abcd"ƒ is fitted for use with  Control.Foldl, thus:.S.print $ L.purely S.scan L.list $ each [3..5][][3][3,4][3,4,5]„HStrict left scan, accepting a monadic function. It can be used with FoldMs from  Control.Foldl using impurely;. Here we yield a succession of vectors each recording Ylet v = L.impurely scanM L.vector $ each [1..4::Int] :: Stream (Of (U.Vector Int)) IO () S.print v fromList [] fromList [1]fromList [1,2]fromList [1,2,3]fromList [1,2,3,4]†:Streams the number of seconds from the beginning of action@Thus, to mark times of user input we might write something like:/S.toList $ S.take 3 $ S.zip S.seconds S.stdinLna<Enter>b<Enter>c<Enter>9[(0.0,"a"),(1.088711,"b"),(3.7289649999999996,"c")] :> ()ATo restrict user input to some number of seconds, we might write:IS.toList $ S.zipWith (flip const) (S.takeWhile (< 5) S.seconds) S.stdinLn one<Enter> two<Enter> three<Enter> four<Enter> five<Enter>)["one","two","three","four","five"] :> ()‡ Like the 8 but streaming. The result type is a stream of a's, but is not accumulatedj; the effects of the elements of the original stream are interleaved in the resulting stream. Compare: wsequence :: Monad m => [m a] -> m [a] sequence :: Monad m => Stream (Of (m a)) m r -> Stream (Of a) m rThis obeys the rule‰Fold a  of numbers into their sumŠFold a 0 of numbers into their sum with the return value D mapped S.sum :: Stream (Stream (Of Int)) m r -> Stream (Of Int) m rS.sum $ each [1..10]55 :> ()2(n :> rest) <- S.sum $ S.splitAt 3 $ each [1..10]print n6((m :> rest') <- S.sum $ S.splitAt 3 restprint m15 S.print rest'789‹?Stream elements until one fails the condition, return the rest.Œ[Split a stream of elements wherever a given element arises. The action is like that of º. AS.stdoutLn $ mapped S.toList $ S.split ' ' $ each "hello world "helloworldSplit a succession of layers after some number, returning a streaming or -- effectful pair. This function is the same as the + exported by the --  Streamingk module, but since this module is imported qualified, it can -- usurp a Prelude name. It specializes to: c splitAt :: (Monad m, Functor f) => Int -> Stream (Of a) m r -> Stream (Of a) m (Stream (Of a) m r)ŽKEnd a stream after n elements; the original return value is thus lost. - preserves this information. Note that, like splitAtF, this function is functor-general, so that, for example, you can takeh not just a number of items from a stream of elements, but a number of substreams and the like.)S.toList $ S.take 3 $ each "pennsylvania" "pen" :> ()-total <- S.sum_ $ S.take 3 S.readLn :: IO Int1<Enter> 10<Enter> 100<Enter> print total111aEnd stream when an element fails a condition; the original return value is lost. By contrast ‹ preserves this information.4Convert an effectful 'Stream (Of a)' into a list of as_Note: Needless to say, this function does not stream properly. It is basically the same as q which, like , ‡X and similar operations on traversable containers is a leading cause of space leaks.‘Convert an effectful ' into a list alongside the return value C mapped toListM :: Stream (Stream (Of a)) m r -> Stream (Of [a]) m ’MInspect the first item in a stream of elements, without a return value. uncons6 provides convenient exit into another streaming type: ˆIOStreams.unfoldM uncons :: Stream (Of a) IO b -> IO (InputStream a) Conduit.unfoldM uncons :: Stream (Of a) m r -> Conduit.Source m a“Build a Stream* by unfolding steps starting from a seed. RThe seed can of course be anything, but this is one natural way to consume a pipes  . Consider:2S.stdoutLn $ S.take 2 $ S.unfoldr P.next P.stdinLn hello<Enter>hellogoodbye<Enter>goodbye8S.stdoutLn $ S.unfoldr P.next (P.stdinLn P.>-> P.take 2) hello<Enter>hellogoodbye<Enter>goodbyeHS.effects $ S.unfoldr P.next (P.stdinLn P.>-> P.take 2 P.>-> P.stdoutLn) hello<Enter>hellogoodbye<Enter>goodbye”AReplace each element in a stream of individual Haskell values (a Stream (Of a) m r) with an associated  functorial step.  qfor str f = concats (with str f) with str f = for str (yields . f) with str f = maps (\(a:>r) -> r <$ f a) strJwith (each [1..3]) (yield . show) & intercalates (yield "--") & S.stdoutLn1--2--3•A singleton streamstdoutLn $ yield "hello"helloS.sum $ do {yield 1; yield 2}3'let prompt = putStrLn "Enter a number:"Glet number = lift (prompt >> readLn) >>= yield :: Stream (Of Int) IO ()&S.toList $ do {number; number; number}Enter a number:1Enter a number:2Enter a number:3 [1,2,3] :> ()–Zip two Streamss —Zip two Streams's using the provided combining function˜ Zip three s with a combining function™Zip three streams together š3View standard input as a 'Stream (Of String) m r'. Ÿ_, by contrast, renders a 'Stream (Of String) m r' to standard output. The names follow  Pipes.PreludestdoutLn stdinLn hello<Enter>hello world<Enter>world^CInterrupted. stdoutLn $ S.map reverse stdinLn hello<Enter>olleh world<Enter>dlrow^CInterrupted.›Read values from », ignoring failed parses$S.sum_ $ S.take 2 S.readLn :: IO Int 10<Enter> 12<Enter>227S.toList $ S.take 3 (S.readLn :: Stream (Of Int) IO ())1<Enter>2<Enter>1@#$%^&*\<Enter>3<Enter> [1,2,3] :> ()œRead Œ s from a œ using ŸTerminates on end of inputfIO.withFile "/usr/share/dict/words" IO.ReadMode $ S.stdoutLn . S.take 3 . S.drop 50000 . S.fromHandle deflagratordeflate deflation<Write a succession of strings to a handle as separate lines.3S.toHandle IO.stdout $ each $ words "one two three"onetwothreež-Print the elements of a stream as they arise.S.print $ S.take 2 S.stdinLnhello"hello"world"world"ŸWrite Œs to ¿ using ÀH; terminates on a broken output pipe (This operation is modelled on ).@S.stdoutLn $ S.take 3 $ S.each $ words "one two three four five"onetwothree Write Œs to ¿ using ÀmThis does not handle a broken output pipe, but has a polymorphic return value, which makes this possible:8rest <- S.stdoutLn' $ S.show $ S.splitAt 3 (each [1..5])123 S.print rest45¡,Read a series of strings as lines to a file.;runResourceT $ S.writeFile "lines.txt" $ S.take 2 S.stdinLn hello<Enter> world<Enter>/runResourceT $ S.print $ S.readFile "lines.txt""hello""world"+, as it is used here, means something like closing_handlesQ; it makes it possible to write convenient, fairly sensible versions of ¡, ¢ and Á. Its use is explained  Hhttps://www.fpcomplete.com/user/snoyberg/library-documentation/resourcethere.¢VWrite a series of strings as lines to a file. The handle is crudely managed with :;runResourceT $ S.writeFile "lines.txt" $ S.take 2 S.stdinLn hello<Enter> world<Enter>/runResourceT $ S.print $ S.readFile "lines.txt""hello""world"šfStore the result of any suitable fold over a stream, keeping the stream for further manipulation. store f = f . duplicate :)S.print $ S.store S.product $ each [1..4]123424 :> ()9S.print $ S.store S.sum $ S.store S.product $ each [1..4]123410 :> (24 :> ())uHere the sum (10) and the product (24) have been 'stored' for use when finally we have traversed the stream with ž . Needless to say, a second passM is excluded conceptually, so the folds that you apply successively with storey are performed simultaneously, and in constant memory -- as they would be if, say, you linked them together with  Control.Fold:xL.impurely S.foldM (liftA3 (\a b c -> (b,c)) (L.sink print) (L.generalize L.sum) (L.generalize L.product)) $ each [1..4]1234 (10,24) :> ()"Fusing folds after the fashion of  Control.FoldlP will generally be a bit faster than the corresponding succession of uses of šT, but by constant factor that will be completely dwarfed when any IO is at issue.But š  © is Hmuch/ more powerful, as you can see by reflecting on uses like this:wS.sum $ S.store (S.sum . mapped S.product . chunksOf 2) $ S.store (S.product . mapped S.sum . chunksOf 2 )$ each [1..6]21 :> (44 :> (231 :> ()))TIt will be clear that this cannot be reproduced with any combination of lenses,  Control.Fold2 folds, or the like. (See also the discussion of ©.)š+ is intended to be used at types like these ÿ$storeM :: (Monad m => Stream (Of a) m r -> m (Of b r)) -> (Monad n => Stream (Of a) n r -> Stream (Of a) n (Of b r)) storeM = store storeMIO :: (MonadIO m => Stream (Of a) m r -> m (Of b r)) -> ( MonadIO n => Stream (Of a) n r -> Stream (Of a) n (Of b r) storeMIO = store)And similarly for other constraints that  Stream (Of a) inherits, like O. Thus I can filter and write to one file, but nub and write to another: ™runResourceT $ (S.writeFile "hello2.txt" . S.nub) $ store (S.writeFile "hello.txt" . S.filter (/= "world")) $ each ["hello", "world", "goodbye", "world"]:! cat hello.txthellogoodbye:! cat hello2.txthelloworldgoodbye©‡Duplicate the content of stream, so that it can be acted on twice in different ways, but without breaking streaming. Thus, given: S.print $ each ["one","two"]"one""two"S.stdoutLn $ each ["one","two"]onetwoI can as well do:7S.print $ S.stdoutLn $ S.duplicate $ each ["one","two"]one"one"two"two"ÄWhere the actions you are contemplating are each simple folds over the elements, or a selection of elements, then the coupling of the folds is often more straightforwardly effected with  , e.g.;L.purely S.fold (liftA2 (,) L.sum L.product) $ each [1..10](55,3628800) :> () rather than.S.sum $ S.product . S.duplicate $ each [1..10]55 :> (3628800 :> ())A  Control.FoldlE fold can be altered to act on a selection of elements by using K on an appropriate lens. Some such manipulations are simpler and more  -like, using ©:rL.purely S.fold (liftA2 (,) (L.handles (filtered odd) L.sum) (L.handles (filtered even) L.product)) $ each [1..10](25,3840) :> ()becomesMS.sum $ S.filter odd $ S.product $ S.filter even $ S.duplicate $ each [1..10]25 :> (3840 :> ()) or using š IS.sum $ S.filter odd $ S.store (S.product . S.filter even) $ each [1..10]25 :> (3840 :> ())But anything that fold of a Stream (Of a) m r into e.g. an  m (Of b r) that has a constraint on m that is carried over into  Stream f m - e.g. Monad, MonadIO,  MonadResourceg, etc. can be used on the stream. Thus, I can fold over different groupings of the original stream:s(S.toList . mapped S.toList . chunksOf 5) $ (S.toList . mapped S.toList . chunksOf 3) $ S.duplicate $ each [1..10]D[[1,2,3,4,5],[6,7,8,9,10]] :> ([[1,2,3],[4,5,6],[7,8,9],[10]] :> ())hThe procedure can be iterated as one pleases, as one can see from this (otherwise unadvisable!) example:¬(S.toList . mapped S.toList . chunksOf 4) $ (S.toList . mapped S.toList . chunksOf 3) $ S.duplicate $ (S.toList . mapped S.toList . chunksOf 2) $ S.duplicate $ each [1..12]€[[1,2,3,4],[5,6,7,8],[9,10,11,12]] :> ([[1,2,3],[4,5,6],[7,8,9],[10,11,12]] :> ([[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]] :> ()))ªThe type +Data.List.unzip :: [(a,b)] -> ([a],[b])might lead us to expect  OStreaming.unzip :: Stream (Of (a,b)) m r -> Stream (Of a) m (Stream (Of b) m r)0which would not stream. Of course, neither does |ÂÃÄÅÆÇCDÈÉÊEFGH·IJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijk¹lmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ªËÌÍÎÏÐÑÒÓm!>?@CDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ªmCD•X“š›œ¡k~€R[\†Ÿ rž¢TUpqO!‡z]^e”SjŽVWPƒ„…}ˆQ©šy’ŒMN‹gf£>?@¥€§Š`_baIJKLЉ|{hilmYZon‘stuvwxdc–—™˜ªEFGH‚uÂÃÄÅÆÇCDÈÉÊEFGH·IJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijk¹lmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ªËÌÍÎÏÐÑÒÓDNoneIN=  !"#$%&'()*+,-./0189:;<=?@ABCDEF= :1/089$!"#.B;<A=?@()&%+,-*'CDEF   Ô !"#$"#%&'(&')&'*&'+,-.,-/012,34,3567869:69;69<,=>,=?,=?01@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„ …†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæàçèéèêëìíîïðññòóôõö÷øùúûüstrea_HxPrpeojtUaD3fOJvU18FC StreamingStreaming.InternalStreaming.Preludeunfoldr duplicate Control.Foldlpurely Data.Maybe catMaybes Data.EitherrightsenumFromData.SetSet Data.ListsequencePipesProducer Pipes.PreludestdoutLnControlFoldlhandlesDataListunzipbaseGHC.Basejoin Data.FunctorvoidliftA3liftA2excep_8GsEeHgaIks3pVGk6GaELJControl.Monad.CatchthrowM MonadThrowmmorp_8dNpUU8QFPe77rrwKAb20bControl.Monad.MorphhoistMFunctorembedMMonadtrans_3eG64VdP2vzGjP6wJiCp5XControl.Monad.Trans.Class MonadTranslifttrans_88TAFm21vtn2NrYUppy50cControl.Monad.Base MonadBaseControl.Monad.IO.ClassMonadIOliftIOresou_5dZgZMYiA0Q8JAIyQrczuNControl.Monad.Trans.Resource runResourceT%Control.Monad.Trans.Resource.Internal liftResourceT MonadResource ResourceTData.Functor.Compose getComposeComposeliftBaseStreamStepEffectReturn bracketStreamdestroy streamFold streamBuildinspectunfoldmapsmapsMmapped decomposerunmapsM_ intercalatesiterTMiterTconcatssplitsAttakeschunksOf distributerepeatsrepeatsM replicatescycles hoistExposed mapsExposed mapsMExposeddestroyExposed unexposedeffectwrapyieldszipsWithzips interleavesswitchseparate unseparateunzipsgroupsOf:>lazilystrictlyfst'snd'allall_anyany_break breakWhenchainconcatconscycledelayeffectsdraineddrop dropWhileeachelemelem_ enumFromThenfilterfilterMfold_foldfoldM_foldMfoldrTfoldrMforgroupBygroupheadhead_ intersperseiteratelastlast_length_lengthmapmapMmapM_mconcatmconcat_minimumminimum_maximummaximum_nextnubproduct_productreadrepeatrepeatM replicate replicateMrereadscanscanMscannedsecondsshowsum_sumspansplitsplitAttake takeWhiletoList_toListunconswithyieldzipzipWithzipWith3zip3stdinLnreadLn fromHandletoHandleprint stdoutLn'readFile writeFile distinguish sumToEither eitherToSum composeToSum sumToComposestore_bind$fMonadResourceStream$fMonadCatchStream$fMonadThrowStream$fMonadBasebStream$fMonadIOStream$fMMonadStream$fMFunctorStream$fMonadTransStream$fApplicativeStream $fMonadStream$fFunctorStreammapOfiditerateM Data.OldListwordsGHC.IO.Handle.FDstdinStringGHC.IO.Handle.TypesHandleGHC.IO.Handle.TexthGetLinestdout System.IOputStrLn appendFileMaybe'Just'Nothing'Maybe_Just_Nothing_SPECSPEC2 $fShow1Of $fRead1Of$fOrd1Of$fEq1Of$fIsStringStream $fMonadOf$fApplicativeOf $fFunctorOf $fMonoidOf