h$uSI       !"#$%&'() * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { |}~                                                                !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"""""""""""""""""""""""""""""""""""""""""""""""""""##########################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % % % % % % % % % % % % % % % % % & & & & & & & & & & & & & ' ' ' ' ' ' ' ' ' ' ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + , , , , , , , , , , - - - - - - - - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . / / / / / / / / / / / / / / / / 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0                                                1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 67!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHC Safe-Inferred "V 8!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone& streamlywrite FD buffer offset length tries to write data on the given filesystem fd (cannot be a socket) up to sepcified length starting from the given offset in the buffer. The write will not block the OS thread, it may suspend the Haskell thread until write can proceed. Returns the actual amount of data written. streamlyKeep writing in a loop until all data in the buffer has been written. streamlywrite FD iovec count tries to write data on the given filesystem fd (cannot be a socket) from an iovec with specified number of entries. The write will not block the OS thread, it may suspend the Haskell thread until write can proceed. Returns the actual amount of data written. streamlyKeep writing an iovec in a loop until all the iovec entries are written. BSD3streamly@composewell.com experimentalGHCNone&^!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHC Safe-Inferred'9streamlyDiscard any exceptions or value returned by an effectful action.Internal&(c) 2018-2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone' (c) Roman Leshchinskiy 2009-2012 BSD-stylestreamly@composewell.com non-portableNone 1streamlyMutable primitive arrays associated with a primitive state token. These can be written to and read from in a monadic context that supports sequencing such as   or ST. Typically, a mutable primitive array will be built and then convert to an immutable primitive array using !. However, it is also acceptable to simply discard a mutable primitive array since it lives in managed memory and will be garbage collected when no longer referenced.streamly4Arrays of unboxed elements. This accepts types like  ,  ,  , and  *, as well as their fixed-length variants (Word8, Word16+, etc.). Since the elements are unboxed, a ? is strict in its elements. This differs from the behavior of Array!, which is lazy in its elements.streamlyCreate a new mutable primitive array of the given length. The underlying memory is left uninitialized.streamlyResize a mutable primitive array. The new size is given in elements.This will either resize the array in-place or, if not possible, allocate the contents into a new, unpinned array and copy the original array's contents.+To avoid undefined behaviour, the original ( shall not be accessed anymore after a  has been performed. Moreover, no reference to the old one should be kept in order to allow garbage collection of the original  in case a new  had to be allocated.streamlyShrink a mutable primitive array. The new size is given in elements. It must be smaller than the old size. The array will be resized in place. This function is only available when compiling with GHC 7.10 or newer. streamly$Write an element to the given index.!streamlyConvert a mutable byte array to an immutable one without copying. The array should not be modified after the conversion."streamly0Read a primitive value from the primitive array.#streamly2Get the size, in elements, of the primitive array.$streamly2Lazy right-associated fold over the elements of a .%streamly3Strict left-associated fold over the elements of a .&streamly'streamlyLexicographic ordering. Subject to change between major versions.(streamlystreamlynew sizestreamlynew size streamlyarraystreamlyindexstreamlyelement  !"#$%  "!#$% !(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHC Safe-Inferred3)streamlyA ) is a special type of Fold? that does not accumulate any value, but runs only effects. A ) has no state to maintain therefore can be a bit more efficient than a Fold with () as the state, especially when )s are composed with other operations. A Sink can be upgraded to a Fold, but a Fold! cannot be converted into a Sink.)*)* (c) 2015 Dan DoelBSD3streamly@composewell.com non-portableNone3567A/streamly!Create a new small mutable array.0streamly5Read the element at a given index in a mutable array.1streamly6Write an element at the given idex in a mutable array.2streamly)Look up an element in an immutable array.The purpose of returning a result using a monad is to allow the caller to avoid retaining references to the array. Evaluating the return value will cause the array lookup to be performed, even though it may not require the element of the array to be evaluated (which could throw an exception). For instance: data Box a = Box a ... f sa = case indexSmallArrayM sa 0 of Box x -> ...x" is not a closure that references sa% as it would be if we instead wrote: let x = indexSmallArray sa 0And does not prevent sa from being garbage collected. Note that   is not adequate for this use, as it is a newtype, and cannot be evaluated without evaluating the element.3streamly)Look up an element in an immutable array.4streamlyRead a value from the immutable array at the given index, returning the result in an unboxed unary tuple. This is currently used to implement folds.5streamly/Create a copy of a slice of an immutable array.6streamly,Create a copy of a slice of a mutable array.7streamlyCreate an immutable array corresponding to a slice of a mutable array.-transformed monads, for example, will not work right at all.@streamly*Strict map over the elements of the array.Bstreamly Create a - from a list of a known length. If the length of the list does not match the given length, this throws an exception.Cstreamly Create a - from a list.EstreamlyGstreamlyKstreamlyUstreamlyLexicographic ordering. Subject to change between major versions.VstreamlyXstreamly /streamlysizestreamlyinitial contents0streamlyarraystreamlyindex1streamlyarraystreamlyindexstreamly new element2streamlyarraystreamlyindex3streamlyarraystreamlyindex5streamlysourcestreamlyoffsetstreamlylength6streamlysourcestreamlyoffsetstreamlylength7streamlysourcestreamlyoffsetstreamlylength9streamlysourcestreamlyoffsetstreamlylength;streamly destinationstreamlydestination offsetstreamlysourcestreamly source offsetstreamlylength<streamly destinationstreamlydestination offsetstreamlysourcestreamly source offsetstreamlylength+,-./0123456789:;<=>?@ABC-.+,/01;<32456789A:=>CB@? 1 !(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHC Safe-Inferred?By\]^`_^`_\] !(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone #$?C5hstreamly(Lazy right associative fold to a stream. \^`_abcdefghi \^`_abcedfghi (c) 2019 Composewell Technologies (c) 2013 Gabriel GonzalezBSD3streamly@composewell.com experimentalGHC Safe-InferredD\jstreamly A strict  mstreamly A strict  vstreamly#Convert strict Maybe' to lazy Maybe jklmnopqrstuv turspqmnovjkl!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHC Safe-InferredGU~streamlyRepresents a stateful transformation over an input stream of values of type a to outputs of type b in   m.streamlyThe composed pipe distributes the input to both the constituent pipes and zips the output of the two using a supplied zipping function.streamlyThe composed pipe distributes the input to both the constituent pipes and merges the outputs of the two.streamlyLift a pure function to a |.streamlyCompose two pipes such that the output of the second pipe is attached to the input of the first pipe. |}~ |}~!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHC Safe-Inferred #$?H9streamlyLift a monadic function to a |.||(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHC Safe-InferredKstreamlyRun an action forever periodically at the given frequency specified in per second (Hz).streamlyRun a computation on every clock tick, the clock runs at the specified frequency. It allows running a computation at high frequency efficiently by maintaining a local clock and adjusting it with the provided base clock at longer intervals. The first argument is a base clock returning some notion of time in microseconds. The second argument is the frequency in per second (Hz). The third argument is the action to run, the action is provided the local time as an argument.(c) 2019 Harendra KumarBSD3streamly@composewell.com experimentalGHCNoneUostreamlyRelative times are relative to some arbitrary point of time. Unlike - they are not relative to a predefined epoch.streamly;Absolute times are relative to a predefined epoch in time.  represents times using  which can represent times up to ~292 billion years at a nanosecond resolution.streamly8A type class for converting between units of time using   as the intermediate representation with a nanosecond resolution. This system of units can represent up to ~292 years at nanosecond resolution with fast arithmetic operations.NOTE: Converting to and from units may truncate the value depending on the original value and the size and resolution of the destination unit.streamly5A type class for converting between time units using   as the intermediate and the widest representation with a nanosecond resolution. This system of units can represent arbitrarily large times but provides least efficient arithmetic operations due to   arithmetic.NOTE: Converting to and from units may truncate the value depending on the original value and the size and resolution of the destination unit.8A type class for converting between units of time using  as the intermediate representation. This system of units can represent up to ~292 billion years at nanosecond resolution with reasonably efficient arithmetic operations.NOTE: Converting to and from units may truncate the value depending on the original value and the size and resolution of the destination unit.streamlyData type to represent practically large quantities of time efficiently. It can represent time up to ~292 billion years at nanosecond resolution.streamlysecondsstreamly nanosecondsstreamlyAn   time representation with a millisecond resolution. It can represent time up to ~292 million years.streamlyAn   time representation with a microsecond resolution. It can represent time up to ~292,000 years.streamlyAn   time representation with a nanosecond resolution. It can represent time up to ~292 years.streamly Convert a  to an absolute time.streamlyConvert absolute time to a .streamly Convert a  to a relative time.streamlyConvert relative time to a .streamly/Difference between two absolute points of time.streamlyConvert nanoseconds to a string showing time in an appropriate unit.(c) 2019 Harendra Kumar (c) 2009-2012, Cetin Sert (c) 2010, Eugene KirpichovBSD3streamly@composewell.com experimentalGHCNone8a streamlyClock types. A clock may be system-wide (that is, visible to all processes) or per-process (measuring time that is meaningful only within a process). All implementations shall support CLOCK_REALTIME. (The only suspend-aware monotonic is CLOCK_BOOTTIME on Linux.)streamlyThe identifier for the system-wide monotonic clock, which is defined as a clock measuring real time, whose value cannot be set via  clock_settime and which cannot have negative clock jumps. The maximum possible clock jump shall be implementation defined. For this clock, the value returned by  represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. Note that the absolute value of the monotonic clock is meaningless (because its origin is arbitrary), and thus there is no need to set it. Furthermore, realtime applications can rely on the fact that the value of this clock is never set.streamlyThe identifier of the system-wide clock measuring real time. For this clock, the value returned by  represents the amount of time (in seconds and nanoseconds) since the Epoch.streamlyThe identifier of the CPU-time clock associated with the calling process. For this clock, the value returned by  represents the amount of execution time of the current process.streamlyThe identifier of the CPU-time clock associated with the calling OS thread. For this clock, the value returned by  represents the amount of execution time of the current OS thread.streamly(since Linux 2.6.28; Linux and Mac OSX) Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments or the incremental adjustments performed by adjtime(3).streamly(since Linux 2.6.32; Linux and Mac OSX) A faster but less precise version of CLOCK_MONOTONIC. Use when you need very fast, but not fine-grained timestamps.streamly(since Linux 2.6.39; Linux and Mac OSX) Identical to CLOCK_MONOTONIC, except it also includes any time that the system is suspended. This allows applications to get a suspend-aware monotonic clock without having to deal with the complications of CLOCK_REALTIME, which may have discontinuities if the time is changed using settimeofday(2).streamly(since Linux 2.6.32; Linux-specific) A faster but less precise version of CLOCK_REALTIME. Use when you need very fast, but not fine-grained timestamps.  (c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone->?qstreamlyA monad that can perform concurrent or parallel IO operations. Streams that can be composed concurrently require the underlying monad to be .streamly6Specifies the stream yield rate in yields per second (Hertz*). We keep accumulating yield credits at . At any point of time we allow only as many yields as we have accumulated as per  since the start of time. If the consumer or the producer is slower or faster, the actual rate may fall behind or exceed . We try to recover the gap between the two by increasing or decreasing the pull rate from the producer. However, if the gap becomes more than $ we try to recover only as much as . puts a bound on how low the instantaneous rate can go when recovering the rate gap. In other words, it determines the maximum yield latency. Similarly,  puts a bound on how high the instantaneous rate can go when recovering the rate gap. In other words, it determines the minimum yield latency. We reduce the latency by increasing concurrency, therefore we can say that it puts an upper bound on concurrency.If the ; is 0 or negative the stream never yields a value. If the / is 0 or negative we do not attempt to recover.streamlyThe lower rate limitstreamly"The target rate we want to achievestreamlyThe upper rate limitstreamlyMaximum slack from the goalstreamlyAn SVar or a Stream Var is a conduit to the output from multiple streams running concurrently and asynchronously. An SVar can be thought of as an asynchronous IO handle. We can write any number of streams to an SVar in a non-blocking manner and then read them back at any time at any pace. The SVar would run the streams asynchronously and accumulate results. An SVar may not really execute the stream completely and accumulate all the results. However, it ensures that the reader can read the results at whatever paces it wants to read. The SVar monitors and adapts to the consumer's pace.An SVar is a mini scheduler, it has an associated workLoop that holds the stream tasks to be picked and run by a pool of worker threads. It has an associated output queue where the output stream elements are placed by the worker threads. A outputDoorBell is used by the worker threads to intimate the consumer thread about availability of new results in the output queue. More workers are added to the SVar by  fromStreamVar on demand if the output produced is not keeping pace with the consumer. On bounded SVars, workers block on the output queue to provide throttling of the producer when the consumer is not pulling fast enough. The number of workers may even get reduced depending on the consuming pace.New work is enqueued either at the time of creation of the SVar or as a result of executing the parallel combinators i.e. <| and <|>< when the already enqueued computations get evaluated. See joinStreamVarAsync.streamlyIdentify the type of the SVar. Two computations using the same style can be scheduled on the same SVar.streamly=Sorting out-of-turn outputs in a heap for Ahead style streamsstreamly7Events that a child thread may send to a parent thread.streamly0Adapt the stream state from one type to another.streamlyFork a thread that is automatically killed as soon as the reference to the returned threadId is garbage collected.streamlyThis function is used by the producer threads to queue output for the consumer thread to consume. Returns whether the queue has more space.streamlyIn contrast to pushWorker which always happens only from the consumer thread, a pushWorkerPar can happen concurrently from multiple threads on the producer side. So we need to use a thread safe modification of workerThreads. Alternatively, we can use a CreateThread event to avoid using a CAS based modification.streamlyWrite a stream to an  in a non-blocking manner. The stream can then be read back from the SVar using fromSVar.(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone&-0>?streamlySame as .streamlyClass of types that can represent a stream of elements of some type a in some monad m.streamlyConstructs a stream by adding a monadic action at the head of an existing stream. For example: > toList $ getLine `consM` getLine `consM` nil hello world ["hello","world"] Concurrent (do not use  parallely to construct infinite streams)streamlyOperator equivalent of . We can read it as "parallel colon" to remember that | comes before :. > toList $ getLine |: getLine |: nil hello world ["hello","world"]  let delay = threadDelay 1000000 >> print 1 drain $ serially $ delay |: delay |: delay |: nil drain $ parallely $ delay |: delay |: delay |: nil Concurrent (do not use  parallely to construct infinite streams)streamly The type  Stream m a/ represents a monadic stream of values of type a% constructed using actions in monad m. It uses stop, singleton and yield continuations equivalent to the following direct style type:  toList $ 1 `cons` 2 `cons` 3 `cons` nil [1,2,3] streamlyOperator equivalent of . &> toList $ 1 .: 2 .: 3 .: nil [1,2,3] streamlyAn empty stream. > toList nil [] streamly(An empty stream producing a side effect. '> toList (nilM (print "nil")) "nil" [] InternalstreamlyFold a stream by providing an SVar, a stop continuation, a singleton continuation and a yield continuation. The stream would share the current SVar passed via the State.streamlyFold a stream by providing a State, stop continuation, a singleton continuation and a yield continuation. The stream will not use the SVar passed via State.streamly(Lazy right associative fold to a stream.streamlyLike / but shares the SVar state across computations.streamly-Lazy right fold with a monadic step function.streamlyPolymorphic version of the  operation  of SerialT. Appends two streams sequentially, yielding all elements from the first stream, and then all elements from the second stream.streamlyDetach a stream from an SVarstreamly Perform a  using a specified concat strategy. The first argument specifies a merge or concat function that is used to merge the streams generated by the map function. For example, the concat function could be , parallel, async, ahead% or any other zip or merge function.**5555(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone -0>?SstreamlySame as yieldMstreamly .repeatM = fix . cons repeatM = cycle1 . yield 9Generate an infinite stream by repeating a monadic value.Internalstreamly fromFoldable =     Construct a stream from a   containing pure values:streamlyLazy right associative fold.streamly9Right associative fold to an arbitrary transformer monad.streamlyStrict left fold with an extraction function. Like the standard strict left fold, but applies a user supplied extraction function (the third argument) to the folded value at the end. This is designed to work with the foldl library. The suffix x is a mnemonic for extraction.Note that the accumulator is always evaluated including the initial value.streamlyStrict left associative fold.streamlyLike foldx#, but with a monadic step function.streamlyLike " but with a monadic step function.streamlyLazy left fold to a stream.streamly1Lazy left fold to an arbitrary transformer monad.streamly >drain = foldl' (\_ _ -> ()) () drain = mapM_ (\_ -> return ())streamlyIterate a lazy function f of the shape `m a -> t m a` until it gets fully defined i.e. becomes independent of its argument action, then return the resulting value of the function (`t m a`).It can be used to construct a stream that uses a cyclic definition. For example: import Streamly.Internal.Prelude as S import System.IO.Unsafe (unsafeInterleaveIO) main = do S.mapM_ print $ S.mfix $ x -> do a <- S.fromList [1,2] b <- S.fromListM [return 3, unsafeInterleaveIO (fmap fst x)] return (a, b) Note that the function f2 must be lazy in its argument, that's why we use unsafeInterleaveIO because IO monad is strict.Internalstreamly/Extract the last element of the stream, if any.streamlyApply a monadic action to each element of the stream and discard the output of the action.streamly7Zip two streams serially using a pure zipping function.streamly:Zip two streams serially using a monadic zipping function.(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone?1streamlyPull a stream from an SVar.streamlyWrite a stream to an  in a non-blocking manner. The stream can then be read back from the SVar using .streamlyPull a stream from an SVar.(c) 2019 Composewell Technologies (c) 2013 Gabriel GonzalezBSD3streamly@composewell.com experimentalGHCNone?streamlyExperimental type to provide a side input to the fold for generating the initial state. For example, if we have to fold chunks of a stream and write each chunk to a different file, then we can generate the file name using a monadic action. This is a generalized version of .streamlyFold   step   inject   extractstreamlyRepresents a left fold over an input stream consisting of values of type a to a single value of type b in   m.$The fold uses an intermediate state s as accumulator. The step function updates the state and returns the new state. When the fold is done the final result of the fold is extracted from the intermediate state using the extract function.streamlyFold   step   initial   extractstreamlyConvert more general type  into a simpler type streamlyBuffers the input stream to a list in the reverse order of the input.Warning! working on large lists accumulated as buffers in memory could be very inefficient, consider using Streamly.Array instead.streamly (lmap f fold) maps the function f on the input of the fold.?S.fold (FL.lmap (\x -> x * x) FL.sum) (S.enumerateFromTo 1 100)338350streamly(lmapM f fold) maps the monadic function f on the input of the fold.streamly2Include only those elements that pass a predicate.%S.fold (lfilter (> 5) FL.sum) [1..10]40streamlyLike  but with a monadic predicate.streamly(Transform a fold from a pure input to a   input, consuming only   values.streamly Take first n/ elements from the stream and discard the rest.streamlyTakes elements from the input as long as the predicate succeeds.streamlyModify the fold such that when the fold is done, instead of returning the accumulator, it returns a fold. The returned fold starts from where we left i.e. it uses the last accumulator value as the initial value of the accumulator. Thus we can resume the fold later and feed it more input. > do more <- S.fold (FL.duplicate FL.sum) (S.enumerateFromTo 1 10) evenMore <- S.fold (FL.duplicate more) (S.enumerateFromTo 11 20) S.fold evenMore (S.enumerateFromTo 21 30) 465streamlyRun the initialization effect of a fold. The returned fold would use the value returned by this effect as its initial value.streamlyRun one step of a fold and store the accumulator as an initial value in the returned fold.streamlyFor every n input items, apply the first fold and supply the result to the next fold.streamlyGroup the input stream into windows of n second each and then fold each group using the provided fold function.For example, we can copy and distribute a stream to multiple folds where each fold can group the input differently e.g. by one second, one minute and one hour windows respectively and fold each resulting stream of folds.  -----Fold m a b----|-Fold n a c-|-Fold n a c-|-...-|----Fold m a c streamly&Combines the fold outputs using their   instances.streamly Combines the fold outputs (type b) using their   instances.streamly Combines the fold outputs (type b) using their   instances.streamly,Combines the outputs of the folds (the type b) using their   instances.streamly,Combines the outputs of the folds (the type b) using their  instances.streamlyThe fold resulting from   distributes its input to both the argument folds and combines their output using the supplied function.streamly4Maps a function on the output of the fold (the type b).(c) 2018 Harendra Kumar (c) Roman Leshchinskiy 2008-2010BSD3streamly@composewell.com experimentalGHCNone &->?RstreamlyA stream consists of a step function that generates the next step given a current state, and the current state.streamlyA stream is a succession of s. A < produces a single value and the next state of the stream. 3 indicates there are no more values in the stream.streamlyMap a monadic function over a streamlyCreate a singleton  from a pure value.streamlyCreate a singleton  from a monadic action.streamly#Convert a list of pure values to a streamly%Compare two streams lexicographically%&!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone streamly Convert a ) to a . When you want to compose sinks and folds together, upgrade a sink to a fold before composing.streamly8Distribute one copy each of the input to both the sinks.  |-------Sink m a ---stream m a---| |-------Sink m a > let pr x = Sink.drainM (putStrLn . ((x ++ " ") ++) . show) > sink (Sink.tee (pr "L") (pr "R")) (S.enumerateFromTo 1 2) L 1 R 1 L 2 R 2 streamly?Distribute copies of the input to all the sinks in a container.  |-------Sink m a ---stream m a---| |-------Sink m a | ...  > let pr x = Sink.drainM (putStrLn . ((x ++ " ") ++) . show) > sink (Sink.distribute [(pr "L"), (pr "R")]) (S.enumerateFromTo 1 2) L 1 R 1 L 2 R 2 4This is the consumer side dual of the producer side   operation.streamlyDemultiplex to multiple consumers without collecting the results. Useful to run different effectful computations depending on the value of the stream elements, for example handling network packets of different types using different handlers.  |-------Sink m a -----stream m a-----Map-----| |-------Sink m a | ... > let pr x = Sink.drainM (putStrLn . ((x ++ " ") ++) . show) > let table = Data.Map.fromList [(1, pr "One"), (2, pr "Two")] in Sink.sink (Sink.demux id table) (S.enumerateFromTo 1 100) One 1 Two 2 streamlySplit elements in the input stream into two parts using a monadic unzip function, direct each part to a different sink.  |-------Sink m b -----Stream m a----(b,c)--| |-------Sink m c > let pr x = Sink.drainM (putStrLn . ((x ++ " ") ++) . show) in Sink.sink (Sink.unzip return (pr "L") (pr "R")) (S.yield (1,2)) L 1 R 2 streamlySame as  but with a pure unzip function.streamly&Map a pure function on the input of a ).streamly)Map a monadic function on the input of a ).streamlyFilter the input of a )! using a pure predicate function.streamlyFilter the input of a )$ using a monadic predicate function.streamlyDrain all input, running the effects and discarding the results.streamly drainM f = lmapM f drainThis hash is often used in Rabin-Karp string search algorithm.See *https://en.wikipedia.org/wiki/Rolling_hashstreamly Compute an  + sized polynomial rolling hash of a stream. -rollingHash = rollingHashWithSalt defaultSaltstreamly Compute an   sized polynomial rolling hash of the first n elements of a stream. 'rollingHashFirstN = ltake n rollingHashstreamly;Fold an input stream consisting of monoidal elements using   and  . 6S.fold FL.mconcat (S.map Sum $ S.enumerateFromTo 1 10)streamly foldMap f = map f mconcatMake a fold from a pure function that folds the output of the function using   and  . 0S.fold (FL.foldMap Sum) $ S.enumerateFromTo 1 10streamly foldMapM f = mapM f mconcatMake a fold from a monadic function that folds the output of the function using   and  .  ("Hello ","World!")splitAt_ (-1) [1,2,3]> ([],[1,2,3])splitAt_ 0 [1,2,3]> ([],[1,2,3])splitAt_ 1 [1,2,3] > ([1],[2,3])splitAt_ 3 [1,2,3]> ([1,2,3],[])splitAt_ 4 [1,2,3]> ([1,2,3],[])InternalstreamlyBreak the input stream into two groups, the first group takes the input as long as the predicate applied to the first element of the stream and next input element holds /, the second group takes the rest of the input.Internalstreamly span p f1 f2 composes folds f1 and f2 such that f1. consumes the input as long as the predicate p is . f2! consumes the rest of the input. let span_ p xs = S.fold (S.span p FL.toList FL.toList) $ S.fromList xsspan_ (< 1) [1,2,3]> ([],[1,2,3])span_ (< 2) [1,2,3] > ([1],[2,3])span_ (< 4) [1,2,3]> ([1,2,3],[])Internalstreamly break p = span (not . p)'Break as soon as the predicate becomes .  break p f1 f2 composes folds f1 and f2 such that f11 stops consuming input as soon as the predicate p becomes $. The rest of the input is consumed f2.This is the binary version of splitBy. let break_ p xs = S.fold (S.break p FL.toList FL.toList) $ S.fromList xsbreak_ (< 1) [3,2,1]> ([3,2,1],[])break_ (< 2) [3,2,1] > ([3,2],[1])break_ (< 4) [3,2,1]> ([],[3,2,1])InternalstreamlyLike  but applies the predicate in a rolling fashion i.e. predicate is applied to the previous and the next input elements.InternalstreamlyDistribute one copy of the stream to each fold and zip the results.  |-------Fold m a b--------| ---stream m a---| |---m (b,c) |-------Fold m a c--------| >S.fold (FL.tee FL.sum FL.length) (S.enumerateFromTo 1.0 100.0) (5050.0,100)streamlyDistribute one copy of the stream to each fold and collect the results in a container.  |-------Fold m a b--------| ---stream m a---| |---m [b] |-------Fold m a b--------| | | ... S.fold (FL.distribute [FL.sum, FL.length]) (S.enumerateFromTo 1 5)[15,5]4This is the consumer side dual of the producer side  operation.streamlyLike  but for folds that return (), this can be more efficient than ' as it does not need to maintain state.streamlyCompose two folds such that the combined fold accepts a stream of   and routes the  values to the first fold and  values to the second fold. partition = partitionBy idstreamlyFold a stream of key value pairs using a map of specific folds for each key into a map from keys to the results of fold outputs of the corresponding values. > let table = Data.Map.fromList [("SUM", FL.sum), ("PRODUCT", FL.product)] input = S.fromList [("SUM",1),("PRODUCT",2),("SUM",3),("PRODUCT",4)] in S.fold (FL.demux table) input fromList [(PRODUCT,8),(SUM,4)] streamlyGiven a stream of key value pairs and a map from keys to folds, fold the values for each key using the corresponding folds, discarding the outputs. > let prn = FL.drainBy print > let table = Data.Map.fromList [("ONE", prn), ("TWO", prn)] input = S.fromList [("ONE",1),("TWO",2)] in S.fold (FL.demux_ table) input One 1 Two 2 streamlyGiven an input stream of key value pairs and a fold for values, fold all the values belonging to each key. Useful for map/reduce, bucketizing the input in different bins or for generating histograms. > let input = S.fromList [("ONE",1),("ONE",1.1),("TWO",2), ("TWO",2.2)] in S.fold (FL.classify FL.toList) input fromList [("ONE",[1.1,1.0]),("TWO",[2.2,2.0])] streamlySend the elements of tuples in a stream of tuples through two different folds.  |-------Fold m a x--------| ---------stream of (a,b)--| |----m (x,y) |-------Fold m b y--------| 4This is the consumer side dual of the producer side  operation.streamlyApply a terminating fold repeatedly to the input of another fold.Compare with: Streamly.Prelude.concatMap, Streamly.Prelude.foldChunks Unimplemented!(c) 2020 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone#streamly(This exception is used for two purposes:When a parser ultimately fails, the user of the parser is intimated via this exception.When the "extract" function of a parser needs to throw an error.Internalstreamly7A parser is a fold that can fail and is represented as Parser step initial extract'. Before we drive a parser we call the initial action to retrieve the initial state of the fold. The parser driver invokes step with the state returned by the previous step and the next input element. It results into a new state and a command to the driver represented by  type. The driver keeps invoking the step function until it stops or fails. At any point of time the driver can call extract to inspect the result of the fold. It may result in an error or an output value.InternalstreamlyThe return type of a  step.A parser is driven by a parse driver one step at a time, at any time the driver may extract the result of the parser. The parser may ask the driver to backtrack at any point, therefore, the driver holds the input up to a point of no return in a backtracking buffer. The buffer grows or shrinks based on the return values of the parser step execution.When a parser step is executed it generates a new intermediate state of the parse result along with a command to the driver. The command tells the driver whether to keep the input stream for a potential backtracking later on or drop it, and how much to keep. The constructors of ' represent the commands to the driver.InternalstreamlyYield offset state indicates that the parser has yielded a new result which is a point of no return. The result can be extracted using extract%. The driver drops the buffer except offset elements before the current position in stream. The rule is that if a parser has yielded at least once it cannot return a failure result.streamlySkip offset state indicates that the parser has consumed the current input but no new result has been generated. A new state# is generated. However, if we use extract on state. it will generate a result from the previous Yield. When offset is non-zero it is a backward offset from the current position in the stream from which the driver will feed the next input to the parser. The offset cannot be beyond the latest point of no return created by Yield.streamlyStop offset result asks the driver to stop driving the parser because it has reached a fixed point and further input will not change the result. offset is the count of unused elements which includes the element on which  occurred.streamlyAn error makes the parser backtrack to the last checkpoint and try another alternative.streamlyA parser that always yields a pure value without consuming any input.InternalstreamlyA parser that always yields the result of an effectful action without consuming any input.InternalstreamlySequential application. Apply two parsers sequentially to an input stream. The input is provided to the first parser, when it is done the remaining input is provided to the second parser. If both the parsers succeed their outputs are combined using the supplied function. The operation fails if any of the parsers fail.This undoes an "append" of two streams, it splits the streams using two parsers and zips the results.This implementation is strict in the second argument, therefore, the following will fail:8S.parse (PR.satisfy (> 0) *> undefined) $ S.fromList [1]InternalstreamlySequential alternative. Apply the input to the first parser and return the result if the parser succeeds. If the first parser fails then backtrack and apply the same input to the second parser and return the result.Note: This implementation is not lazy in the second argument. The following will fail:S.parse (PR.satisfy (> 0) `PR.alt` undefined) $ S.fromList [1..10]InternalstreamlySee documentation of ;.InternalstreamlySee documentation of <.InternalstreamlyA parser that always fails with an error message without consuming any input.InternalstreamlyA parser that always fails with an effectful error message and without consuming any input.Internalstreamly is same as , it aborts the parser.  is same as ), it selects the first succeeding parser.Internalstreamly instance using .Note: The implementation of  is not lazy in the second argument. The following code will fail:=S.parse (PR.satisfy (> 0) <|> undefined) $ S.fromList [1..10]streamly form of .streamlyMonad composition can be used for lookbehind parsers, we can make the future parses depend on the previously parsed values.If we have to parse "a9" or "9a" but not "99" or "aa" we can use the following parser: backtracking :: MonadCatch m => PR.Parser m Char String backtracking = sequence [PR.satisfy isDigit, PR.satisfy isAlpha] 7 sequence [PR.satisfy isAlpha, PR.satisfy isDigit] We know that if the first parse resulted in a digit at the first place then the second parse is going to fail. However, we waste that information and parse the first character again in the second parse only to know that it is not an alphabetic char. By using lookbehind in a  * composition we can avoid redundant work: data DigitOrAlpha = Digit Char | Alpha Char lookbehind :: MonadCatch m => PR.Parser m Char String lookbehind = do x1 <- Digit  PR.satisfy isDigit  Alpha  PR.satisfy isAlpha -- Note: the parse depends on what we parsed already x2 <- case x1 of Digit _ -> PR.satisfy isAlpha Alpha _ -> PR.satisfy isDigit return $ case x1 of Digit x -> [x,x2] Alpha x -> [x,x2] !(c) 2020 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNoneEstreamlyteeWith f p1 p2 distributes its input to both p1 and p2 until both of them succeed or fail and combines their output using f3. The parser succeeds if both the parsers succeed.InternalstreamlyLike  but ends parsing and zips the results, if available, whenever the first parser ends.InternalstreamlyLike  but ends parsing and zips the results, if available, whenever any of the parsers ends or fails. UnimplementedstreamlyShortest alternative. Apply both parsers in parallel but choose the result from the one which consumed least input i.e. take the shortest succeeding parse.InternalstreamlyLongest alternative. Apply both parsers in parallel but choose the result from the one which consumed more input i.e. take the longest succeeding parse.Internal!(c) 2020 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone:streamly:The resulting parse never terminates and never errors out.streamly,S.parse (PR.any (== 0)) $ S.fromList [1,0,1] > Right Truestreamly,S.parse (PR.all (== 0)) $ S.fromList [1,0,1] > Right FalsestreamlyPeek the head element of a stream, without consuming it. Fails if it encounters end of input.?S.parse ((,) <$> PR.peek <*> PR.satisfy (> 0)) $ S.fromList [1](1,1)  peek = lookAhead (satisfy True) Internalstreamly8Succeeds if we are at the end of input, fails otherwise.>S.parse ((,) <$> PR.satisfy (> 0) <*> PR.eof) $ S.fromList [1]> (1,())InternalstreamlyReturns the next element if it passes the predicate, fails otherwise.0S.parse (PR.satisfy (== 1)) $ S.fromList [1,0,1]> 1Internalstreamly Take at most n6 input elements and fold them using the supplied fold. Stops after n elements. Never fails..S.parse (PR.take 1 FL.toList) $ S.fromList [1][1] ,S.chunksOf n f = S.splitParse (FL.take n f) InternalstreamlyStops after taking exactly n input elements.Stops - after n elements.1Fails - if the stream ends before it can collect n elements.4S.parse (PR.takeEQ 4 FL.toList) $ S.fromList [1,0,1]/> "takeEQ: Expecting exactly 4 elements, got 3"InternalstreamlyTake at least n& input elements, but can collect more.Stops - never.,Fails - if the stream ends before producing n elements.4S.parse (PR.takeGE 4 FL.toList) $ S.fromList [1,0,1]5> "takeGE: Expecting at least 4 elements, got only 3"8S.parse (PR.takeGE 4 FL.toList) $ S.fromList [1,0,1,0,1] > [1,0,1,0,1]InternalstreamlyCollect stream elements until an element fails the predicate. The element on which the predicate fails is returned back to the input stream.!Stops - when the predicate fails.Fails - never.S.parse (PR.takeWhile (== 0) FL.toList) $ S.fromList [0,0,1,0,1]> [0,0]We can implement a breakOn using : breakOn p = takeWhile (not p) InternalstreamlyLike 0 but takes at least one element otherwise fails.InternalstreamlyCollect stream elements until an element succeeds the predicate. Drop the element on which the predicate succeeded. The succeeding element is treated as an infix separator which is dropped from the output.$Stops - when the predicate succeeds.Fails - never.S.parse (PR.sliceSepBy (== 1) FL.toList) $ S.fromList [0,0,1,0,1]> [0,0]6S.splitOn pred f = S.splitParse (PR.sliceSepBy pred f)S.toList $ S.splitParse (PR.sliceSepBy (== 1) FL.toList) $ S.fromList [0,0,1,0,1]> [[0,0],[0],[]]InternalstreamlyCollect stream elements until an element succeeds the predicate. Also take the element on which the predicate succeeded. The succeeding element is treated as a suffix separator which is kept in the output segement.$Stops - when the predicate succeeds.Fails - never.S.splitWithSuffix pred f = S.splitParse (PR.sliceEndWith pred f) UnimplementedstreamlyCollect stream elements until an elements passes the predicate, return the last element on which the predicate succeeded back to the input stream. If the predicate succeeds on the first element itself then it is kept in the stream and we continue collecting. The succeeding element is treated as a prefix separator which is kept in the output segement. results. Fails if the input ends or the parser fails before m results are collected. Unimplementedstreamly count n f p collects exactly n sequential parses of parser p using the fold f6. Fails if the input ends or the parser fails before n results are collected. UnimplementedstreamlymanyTill f collect test tries the parser test on the input, if test fails it backtracks and tries collect, after collect succeeds test2 is tried again and so on. The parser stops when test succeeds. The output of test is discarded and the output of collect; is accumulated by the supplied fold. The parser fails if collect fails.Internal''>!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNoneD%%!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone?streamlyAn  Unfold m a b. is a generator of a stream of values of type b from a seed of type a in   m.streamly Unfold step inject!(c) 2018 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHC Safe-Inferred?streamly8Select alphabetic characters in the ascii character set.Internal!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone-streamly;A monad that allows mutable operations using a state token.streamlyA  holds a single  value.streamlyCreate a new mutable variable.streamly$Write a value to a mutable variable.streamlyRead a value from a variable.streamlyModify the value of a mutable variable using a function with strict application.?!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone ?\ !(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone#$?&<streamly Allocate an array that can hold count3 items. The memory of the array is uninitialized.Note that this is internal routine, the reference to this array cannot be given out until the array has been written to and frozen.streamlyAllocate an Array of the given size and run an IO action passing the array start pointer.streamly$Remove the free space from an Array.streamlyReturn element at the specified index without checking the bounds.9Unsafe because it does not check the bounds of the array.streamlyReturn element at the specified index without checking the bounds.streamlyO(1)" Get the byte length of the array.streamlyO(1) Get the length of the array i.e. the number of elements in the array.streamlywriteN n folds a maximum of n' elements from the input stream to an .streamlywriteNAligned alignment n folds a maximum of n' elements from the input stream to an  aligned to the given size.InternalstreamlywriteNAlignedUnmanaged n folds a maximum of n' elements from the input stream to an  aligned to the given size and using unmanaged memory. This could be useful to allocate memory that we need to allocate only once in the lifetime of the program.InternalstreamlyLike  but does not check the array bounds when writing. The fold driver must not call the step function more than n times otherwise it will corrupt the memory and crash. This function exists mainly because any conditional in the step function blocks fusion causing 10x performance slowdown.streamly'Fold the whole input to a single array.-Caution! Do not use this on infinite streams.streamlyLike  but the array memory is aligned according to the specified alignment size. This could be useful when we have specific alignment, for example, cache aligned arrays for lookup table etc.-Caution! Do not use this on infinite streams.streamlyfromStreamArraysOf n stream< groups the input stream into a stream of arrays of size n.streamly Convert an  into a list.streamly Create an  from the first N elements of a list. The array is allocated to size N, if the list terminates before N elements then the array may hold less than N elements.streamly Create an . from a list. The list must be of finite size.streamlyDefault maximum buffer size in bytes, for reading from and writing to IO devices, the value is 32KB minus GHC allocation overhead, which is a few bytes, so that the actual allocation is 32KB.streamlyCoalesce adjacent arrays in incoming stream to form bigger arrays of a maximum specified size. Note that if a single array is bigger than the specified size we do not split it to fit. When we coalesce multiple arrays if the size would exceed the specified size we do not coalesce therefore the actual array size may be less than the specified chunk size.streamly!groupIOVecsOf maxBytes maxEntries= groups arrays in the incoming stream to create a stream of   arrays with a maximum of maxBytes' bytes in each array and a maximum of  maxEntries entries in each array.streamlyCreate two slices of an array without copying the original array. The specified index i( is the first index of the second slice.streamlySplit a stream of arrays on a given separator byte, dropping the separator and coalescing all the arrays between two separators into a single array.77@!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone#$0streamlyA ring buffer is a mutable array of fixed size. Initially the array is empty, with ringStart pointing at the start of allocated memory. We call the next location to be written in the ring as ringHead. Initially ringHead == ringStart. When the first item is added, ringHead points to ringStart + sizeof item. When the buffer becomes full ringHead would wrap around to ringStart. When the buffer is full, ringHead always points at the oldest item in the ring and the newest item added always overwrites the oldest item.When using it we should keep in mind that a ringBuffer is a mutable data structure. We should not leak out references to it for immutable use.streamlyCreate a new ringbuffer and return the ring buffer and the ringHead. Returns the ring and the ringHead, the ringHead is same as ringStart.streamlyInsert an item at the head of the ring, when the ring is full this replaces the oldest item in the ring with the new item. This is unsafe beause ringHead supplied is not verified to be within the Ring. Also, the ringStart foreignPtr must be guaranteed to be alive by the caller.streamlyLike  but compares only N bytes instead of entire length of the ring buffer. This is unsafe because the ringHead Ptr is not checked to be in range.streamlyByte compare the entire length of ringBuffer with the given array, starting at the supplied ringHead pointer. Returns true if the Array and the ringBuffer have identical contents.This is unsafe because the ringHead Ptr is not checked to be in range. The supplied array must be equal to or bigger than the ringBuffer, ARRAY BOUNDS ARE NOT CHECKED.streamly8Fold the buffer starting from ringStart up to the given  using a pure step function. This is useful to fold the items in the ring when the ring is not full. The supplied pointer is usually the end of the ring.>Unsafe because the supplied Ptr is not checked to be in range.streamly5Like unsafeFoldRing but with a monadic step function.streamlyFold the entire length of a ring buffer starting at the supplied ringHead pointer. Assuming the supplied ringHead pointer points to the oldest item, this would fold the ring starting from the oldest item to the newest item in the ring. !(c) 2018 Harendra Kumar (c) Roman Leshchinskiy 2008-2010 (c) The University of Glasgow, 2009BSD3streamly@composewell.com experimentalGHCNone#$&->?B;streamly An empty .streamly An empty  with a side effect.streamly#Can fuse but has O(n^2) complexity.streamly Convert an  into a  by supplying it a seed.streamlyCan be used to enumerate unbounded integrals. This does not check for overflow or underflow for bounded integrals.streamly'Convert a list of monadic actions to a streamlyRun a Parse over a stream.streamly1Run a streaming composition, discard the results.streamly)Performs infix separator style splitting.streamly)Performs infix separator style splitting.streamly1Execute a monadic action for each element of the streamlyconcatMapU unfold stream uses unfold to map the input stream elements to streams and then flattens the generated streams into a single output stream.streamlyInterleave streams (full streams, not the elements) unfolded from two input streams and concat. Stop when the first stream stops. If the second stream ends before the first one then first stream still keeps running alone without any interleaving with the second stream. a1, a2, ... an[b1, b2 ...] => [streamA1, streamA2, ... streamAn] [streamB1, streamB2, ...] => [streamA1, streamB1, streamA2...StreamAn, streamBn] => [a11, a12, ...a1j, b11, b12, ...b1k, a21, a22, ...]streamlyInterleave streams (full streams, not the elements) unfolded from two input streams and concat. Stop when the first stream stops. If the second stream ends before the first one then first stream still keeps running alone without any interleaving with the second stream. a1, a2, ... an[b1, b2 ...] => [streamA1, streamA2, ... streamAn] [streamB1, streamB2, ...] => [streamA1, streamB1, streamA2...StreamAn, streamBn] => [a11, a12, ...a1j, b11, b12, ...b1k, a21, a22, ...]streamlyThe most general bracketing and exception combinator. All other combinators can be expressed in terms of this combinator. This can also be used for cases which are not covered by the standard combinators.InternalstreamlyCreate an IORef holding a finalizer that is called automatically when the IORef is garbage collected. The IORef can be written to with a $ value to deactivate the finalizer.streamlyRun the finalizer stored in an IORef and deactivate it so that it is run only once.streamly?Deactivate the finalizer stored in an IORef without running it.streamly=Run a side effect before the stream yields its first element.streamly5Run a side effect whenever the stream stops normally.streamlyRun a side effect whenever the stream aborts due to an exception. The exception is not caught, simply rethrown.streamlyRun the first action before the stream starts and remember its output, generate a stream using the output, run the second action providing the remembered value as an argument whenever the stream ends normally or due to an exception.streamlyRun a side effect whenever the stream stops normally or aborts due to an exception.streamlyWhen evaluating a stream if an exception occurs, stream evaluation aborts and the specified exception handler is run with the exception as argument.streamlyintersperse after every n itemsstreamlyFold the supplied stream to the SVar asynchronously using Parallel concurrency style. {- INLINE [1] toSVarParallel -}streamlyMake the stream producer and consumer run concurrently by introducing a buffer between them. The producer thread evaluates the input stream until the buffer fills, it blocks if the buffer is full until there is space in the buffer. The consumer consumes the stream lazily from the buffer.InternalstreamlyGenerates a callback and a stream pair. The callback returned is used to queue values to the stream. The stream is infinite, there is no way for the callback to indicate that it is done now.Internalstreamly Take last n/ elements from the stream and discard the rest.streamlybeforestreamlytry (exception handling)streamlyafter, on normal stopstreamly on exceptionstreamlystream generator"!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone #$?_}&streamly,Map a function on the input argument of the . lmap f = concat (singleton f) Internalstreamly+Map an action on the input argument of the .  lmapM f = concat (singletonM f) InternalstreamlySupply the seed to an unfold closing the input end of the unfold.InternalstreamlySupply the first component of the tuple to an unfold that accepts a tuple as a seed resulting in a fold that accepts the second component of the tuple as a seed.InternalstreamlySupply the second component of the tuple to an unfold that accepts a tuple as a seed resulting in a fold that accepts the first component of the tuple as a seed.Internalstreamly Convert an  into an unfold accepting a tuple as an argument, using the argument of the original fold as the second element of tuple and discarding the first element of the tuple.Internalstreamly Convert an  into an unfold accepting a tuple as an argument, using the argument of the original fold as the first element of tuple and discarding the second element of the tuple.Internalstreamly Convert an  that accepts a tuple as an argument into an unfold that accepts a tuple with elements swapped.Internalstreamly Compose an  and a  . Given an  Unfold m a b and a  Fold m b c, returns a monadic action a -> m c representing the application of the fold on the unfolded stream.InternalstreamlyConvert a stream into an &. Note that a stream converted to an  may not be as efficient as an  in some situations.Internalstreamly=Convert a single argument stream generator function into an %. Note that a stream converted to an  may not be as efficient as an  in some situations.Internalstreamly9Convert a two argument stream generator function into an &. Note that a stream converted to an  may not be as efficient as an  in some situations.InternalstreamlyLift a monadic function into an unfold generating a nil stream with a side effect.streamly:Prepend a monadic single element generator function to an .InternalstreamlyLift a monadic effect into an unfold generating a singleton stream.streamlyLift a monadic function into an unfold generating a singleton stream.streamlyLift a pure function into an unfold generating a singleton stream.streamlyIdentity unfold. Generates a singleton stream with the seed as the only element in the stream. identity = singletonM returnstreamly(Generates a stream replicating the seed n times.streamly0Generates an infinite stream repeating the seed.streamly#Convert a list of pure values to a streamly&Convert a list of monadic values to a streamlyCan be used to enumerate unbounded integrals. This does not check for overflow or underflow for bounded integrals.streamlyDistribute the input to two unfolds and then zip the outputs to a single stream. S.mapM_ print $ S.concatUnfold (UF.teeZipWith (,) UF.identity (UF.singleton sqrt)) $ S.fromList [1..10] InternalstreamlyApply the second unfold to each output element of the first unfold and flatten the output in a single stream.InternalstreamlyCreate an outer product (vector product or cartesian product) of the output streams of two unfolds.streamlyMap an unfold generating action to each element of an unfold and flattern the results into a single stream.streamlyThe most general bracketing and exception combinator. All other combinators can be expressed in terms of this combinator. This can also be used for cases which are not covered by the standard combinators.InternalstreamlyThe most general bracketing and exception combinator. All other combinators can be expressed in terms of this combinator. This can also be used for cases which are not covered by the standard combinators.Internalstreamly=Run a side effect before the unfold yields its first element.Internalstreamly5Run a side effect whenever the unfold stops normally. Prefer afterIO over this as the after action in this combinator is not executed if the unfold is partially evaluated lazily and then garbage collected.InternalstreamlyRun a side effect whenever the unfold stops normally or is garbage collected after a partial lazy evaluation.InternalstreamlyRun a side effect whenever the unfold aborts due to an exception.InternalstreamlyRun a side effect whenever the unfold stops normally or aborts due to an exception."Prefer finallyIO over this as the after action in this combinator is not executed if the unfold is partially evaluated lazily and then garbage collected.InternalstreamlyRun a side effect whenever the unfold stops normally, aborts due to an exception or if it is garbage collected after a partial lazy evaluation.Internalstreamlybracket before after between runs the before/ action and then unfolds its output using the between unfold. When the between4 unfold is done or if an exception occurs then the after# action is run with the output of before as argument."Prefer bracketIO over this as the after action in this combinator is not executed if the unfold is partially evaluated lazily and then garbage collected.Internalstreamlybracket before after between runs the before/ action and then unfolds its output using the between unfold. When the between4 unfold is done or if an exception occurs then the after# action is run with the output of before as argument. The after action is also executed if the unfold is paritally evaluated and then garbage collected.InternalstreamlyWhen unfolding if an exception occurs, unfold the exception using the exception unfold supplied as the first argument to .Internalstreamlybeforestreamlytry (exception handling)streamlyafter, on normal stopstreamly on exceptionstreamly unfold to runstreamlybeforestreamlytry (exception handling)streamlyafter, on normal stop, or GCstreamly on exceptionstreamly unfold to run44A!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone?`#(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNonei$ streamly  fromList =     Construct a stream from a list of pure values. This is more efficient than  for serial streams.streamly5Convert a stream into a list in the underlying monad.streamlyLike #, but with a monadic step function.streamlyStrict left fold with an extraction function. Like the standard strict left fold, but applies a user supplied extraction function (the third argument) to the folded value at the end. This is designed to work with the foldl library. The suffix x is a mnemonic for extraction.streamlyStrict left associative fold.streamly&Lazy left fold to a transformer monad.!For example, to reverse a stream: S.toList $ S.foldlT (flip S.cons) S.nil $ (S.fromList [1..5] :: SerialT IO Int)streamly3Strict left scan with an extraction function. Like scanl', but applies a user supplied extraction function (the third argument) at each step. This is designed to work with the foldl library. The suffix x is a mnemonic for extraction.streamly Compare two streams for equalitystreamlyCompare two streamsstreamly A variant of BC that allows you to fold a   container of streams using the specified stream sum operation.  foldWith async $ map return [1..3]Equivalent to:  foldWith f = S.foldMapWith f id Since: 0.1.0 (Streamly)streamly A variant of 9 that allows you to map a monadic streaming action on a   container and then fold it using the specified stream merge operation.  foldMapWith async return [1..3]Equivalent to: =foldMapWith f g xs = S.concatMapWith f g (S.fromFoldable xs) Since: 0.1.0 (Streamly)streamlyLike  but with the last two arguments reversed i.e. the monadic streaming function is the last argument.Equivalent to: !forEachWith = flip S.foldMapWith Since: 0.1.0 (Streamly)$(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone-0>?p streamly>An IO stream whose applicative instance zips streams wAsyncly.streamlyLike  but zips in parallel, it generates all the elements to be zipped concurrently. main = (toList .  $ (,,) <$> s1 <*> s2 <*> s3) >>= print where s1 = fromFoldable [1, 2] s2 = fromFoldable [3, 4] s3 = fromFoldable [5, 6]  [(1,3,5),(2,4,6)] The 6 instance of this type works the same way as that of SerialT.streamly>An IO stream whose applicative instance zips streams serially.streamlystreamlyThe applicative instance of  zips a number of streams serially i.e. it produces one element from each stream serially and then zips all those elements. main = (toList .  $ (,,) <$> s1 <*> s2 <*> s3) >>= print where s1 = fromFoldable [1, 2] s2 = fromFoldable [3, 4] s3 = fromFoldable [5, 6]  [(1,3,5),(2,4,6)] The 6 instance of this type works the same way as that of SerialT.streamlyLike & but using a monadic zipping function.streamly7Zip two streams serially using a pure zipping function. > S.toList $ S.zipWith (+) (S.fromList [1,2,3]) (S.fromList [4,5,6]) [5,7,9] streamlyLike  but zips concurrently i.e. both the streams being zipped are generated concurrently.streamlyLike  but zips concurrently i.e. both the streams being zipped are generated concurrently.streamly(Fix the type of a polymorphic stream as .streamlySame as .streamly(Fix the type of a polymorphic stream as .streamlySame as .  %(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone-0>?Rstreamlystreamly5An interleaving serial IO stream of elements of type a. See ! documentation for more details.streamlyThe  operation for  interleaves the elements from the two streams. Therefore, when a <> b is evaluated, stream a is evaluated first to produce the first element of the combined stream and then stream b is evaluated to produce the next element of the combined stream, and then we go back to evaluating stream a4 and so on. In other words, the elements of stream a- are interleaved with the elements of stream b.Note that evaluation of  a <> b <> c does not schedule a, b and c9 with equal priority. This expression is equivalent to  a <> (b <> c)$, therefore, it fairly interleaves a with the result of b <> c. For example, S.fromList [1,2] <> S.fromList [3,4] <> S.fromList [5,6] :: WSerialT Identity Int would result in [1,3,2,5,4,6]. In other words, the leftmost stream gets the same scheduling priority as the rest of the streams taken together. The same is true for each subexpression on the right.Note that this operation cannot be used to fold a container of infinite streams as the state that it needs to maintain is proportional to the number of streams.The W in the name stands for wide or breadth wise scheduling in contrast to the depth wise scheduling behavior of . !import Streamly import qualified Streamly.Prelude as S main = (S.toList . 7 $ (S.fromList [1,2]) <> (S.fromList [3,4])) >>= print   [1,3,2,4] Similarly, the   instance interleaves the iterations of the inner and the outer loop, nesting loops in a breadth first manner. main = S.drain .  $ do x <- return 1 <> return 2 y <- return 3 <> return 4 S.yieldM $ print (x, y) (1,3) (2,3) (1,4) (2,4) streamlystreamly'A serial IO stream of elements of type a. See ! documentation for more details.streamlyThe  operation for < behaves like a regular append operation. Therefore, when a <> b is evaluated, stream a7 is evaluated first until it exhausts and then stream b7 is evaluated. In other words, the elements of stream b( are appended to the elements of stream a. This operation can be used to fold an infinite lazy container of streams. !import Streamly import qualified Streamly.Prelude as S main = (S.toList . 7 $ (S.fromList [1,2]) <> (S.fromList [3,4])) >>= print   [1,2,3,4] The   instance runs the monadic continuation+ for each element of the stream, serially. main = S.drain . ; $ do x <- return 1 <> return 2 S.yieldM $ print x  1 2 0 nests streams serially in a depth first manner. main = S.drain .  $ do x <- return 1 <> return 2 y <- return 3 <> return 4 S.yieldM $ print (x, y)  (1,3) (1,4) (2,3) (2,4) We call the monadic code being run for each element of the stream a monadic continuation. In imperative paradigm we can think of this composition as nested for loops and the monadic continuation is the body of the loop. The loop iterates for all elements of the stream.)Note that the behavior and semantics of  , including  and  6 instances are exactly like Haskell lists except that 5 can contain effectful actions while lists are pure.In the code above, the : combinator can be omitted as the default stream type is .streamly(Fix the type of a polymorphic stream as .streamly  map = fmap Same as . 5> S.toList $ S.map (+1) $ S.fromList [1,2,3] [2,3,4] streamly(Fix the type of a polymorphic stream as .streamlySame as .streamlyPolymorphic version of the  operation  of . Interleaves two streams, yielding one element from each stream alternately. When one stream stops the rest of the other stream is used in the output stream.streamlyLike : but stops interleaving as soon as the first stream stops.streamlyLike  but stops interleaving as soon as any of the two streams stops.streamlySame as .streamlyBuild a stream by unfolding a monadic step function starting from a seed. The step function returns the next element in the stream and the next seed value. When it is done it returns # and the stream ends. For example, let f b = if b > 3 then return Nothing else print b >> return (Just (b, b + 1)) in drain $ unfoldrM f 0   0 1 2 3 Internal5&!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone streamly Create an  from the first N elements of a stream. The array is allocated to size N, if the stream terminates before N elements then the array may hold less than N elements.Internal streamly Create an  from a stream. This is useful when we want to create a single array from a stream of unknown size. writeN is at least twice as efficient when the size is already known.Note that if the input stream is too large memory allocation for the array may fail. When the stream size is not known, arraysOf followed by processing of indvidual arrays in the resulting stream should be preferred.Internal streamly Convert an  into a stream.Internal streamly Convert an  into a stream in reverse order.Internal streamlyUnfold an array into a stream. streamlyUnfold an array into a stream, does not check the end of the array, the user is responsible for terminating the stream within the array bounds. For high performance application where the end condition can be determined by a terminating fold.Written in the hope that it may be faster than "read", however, in the case for which this was written, "read" proves to be faster even though the core generated with unsafeRead looks simpler.Internal streamly null arr = length arr == 0Internal streamly )last arr = readIndex arr (length arr - 1)Internal streamlyO(1)8 Lookup the element at the given index, starting from 0.Internal streamlyO(1) Write the given element at the given index in the array. Performs in-place mutation of the array.Internal streamlyTransform an array into another array using a stream transformation operation.Internal streamlyFold an array using a .Internal streamly,Fold an array using a stream fold operation.Internal     D!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNoneo  '(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone streamlySpecify the maximum number of threads that can be spawned concurrently for any concurrent combinator in a stream. A value of 0 resets the thread limit to default, a negative value means there is no limit. The default value is 1500.   does not affect  ParallelT5 streams as they can use unbounded number of threads.When the actions in a stream are IO bound, having blocking IO calls, this option can be used to control the maximum number of in-flight IO requests. When the actions are CPU bound this option can be used to control the amount of CPU used by the stream. streamlySpecify the maximum size of the buffer for storing the results from concurrent computations. If the buffer becomes full we stop spawning more concurrent tasks until there is space in the buffer. A value of 0 resets the buffer size to default, a negative value means there is no limit. The default value is 1500.CAUTION! using an unbounded  : value (i.e. a negative value) coupled with an unbounded   value is a recipe for disaster in presence of infinite streams, or very large streams. Especially, it must not be used when   is used in  ZipAsyncM streams as   in applicative zip streams generates an infinite stream causing unbounded concurrent generation with no limit on the buffer or threads. streamly&Specify the pull rate of a stream. A  value resets the rate to default which is unlimited. When the rate is specified, concurrent production may be ramped up or down automatically to achieve the specified yield rate. The specific behavior for different styles of $ specifications is documented under . The effective maximum production rate achieved by a stream is governed by:The   limitThe   limit5The maximum rate that the stream producer can achieve5The maximum rate that the stream consumer can achieve streamlySame as )rate (Just $ Rate (r/2) r (2*r) maxBound)Specifies the average production rate of a stream in number of yields per second (i.e. Hertz). Concurrent production is ramped up or down automatically to achieve the specified average yield rate. The rate can go down to half of the specified rate on the lower side and double of the specified rate on the higher side. streamlySame as %rate (Just $ Rate r r (2*r) maxBound)Specifies the minimum rate at which the stream should yield values. As far as possible the yield rate would never be allowed to go below the specified rate, even though it may possibly go above it at times, the upper limit is double of the specified rate. streamlySame as %rate (Just $ Rate (r/2) r r maxBound)Specifies the maximum rate at which the stream should yield values. As far as possible the yield rate would never be allowed to go above the specified rate, even though it may possibly go below it at times, the lower limit is half of the specified rate. This can be useful in applications where certain resource usage must not be allowed to go beyond certain limits. streamlySame as rate (Just $ Rate r r r 0)Specifies a constant yield rate. If for some reason the actual rate goes above or below the specified rate we do not try to recover it by increasing or decreasing the rate in future. This can be useful in applications like graphics frame refresh where we need to maintain a constant refresh rate. streamly:Print debug information about an SVar when the stream endsInternal (!(c) 2018 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone &567 streamly Just like   except that it has a zipping  instance and no   instance. streamlyList a is a replacement for [a]. streamly3A list constructor and pattern that deconstructs a  ) into its head and tail. Corresponds to : for Haskell lists. streamly?/ streamly4A parallely composing IO stream of elements of type a. See   documentation for more details. streamlyAsync composition with strict concurrent execution of all streams.The  instance of   executes both the streams concurrently without any delay or without waiting for the consumer demand and merges the results as they arrive. If the consumer does not consume the results, they are buffered upto a configured maximum, controlled by the  maxBuffer primitive. If the buffer becomes full the concurrent tasks will block until there is space in the buffer.Both WAsyncT and  , evaluate the constituent streams fairly in a round robin fashion. The key difference is that WAsyncT might wait for the consumer demand before it executes the tasks whereas   starts executing all the tasks immediately without waiting for the consumer demand. For WAsyncT the  maxThreads limit applies whereas for  % it does not apply. In other words, WAsyncT can be lazy whereas   is strict.  is useful for cases when the streams are required to be evaluated simultaneously irrespective of how the consumer consumes them e.g. when we want to race two tasks and want to start both strictly at the same time or if we have timers in the parallel tasks and our results depend on the timers being started at the same time. If we do not have such requirements then AsyncT or AheadT5 are recommended as they can be more efficient than  . main = (toList .  ; $ (fromFoldable [1,2]) <> (fromFoldable [3,4])) >>= print   [1,3,2,4] When streams with more than one element are merged, it yields whichever stream yields first without any bias, unlike the Async style streams.Any exceptions generated by a constituent stream are propagated to the output stream. The output and exceptions from a single stream are guaranteed to arrive in the same order in the resulting stream as they were generated in the input stream. However, the relative ordering of elements from different streams in the resulting stream can vary depending on scheduling and generation delays.Similarly, the   instance of   runs all& iterations of the loop concurrently. import Streamly import qualified Streamly.Prelude( as S import Control.Concurrent main = drain .   $ do n <- return 3 <> return 2 <> return 1 S.yieldM $ do threadDelay (n * 1000000) myThreadId >>= \tid -> putStrLn (show tid ++ ": Delay " ++ show n)  ?ThreadId 40: Delay 1 ThreadId 39: Delay 2 ThreadId 38: Delay 3 Note that parallel composition can only combine a finite number of streams as it needs to retain state for each unfinished stream.5Since: 0.7.0 (maxBuffer applies to ParallelT streams) Since: 0.1.0 streamlyPolymorphic version of the  operation  of  " Merges two streams concurrently. streamlyLike  8 but stops the output as soon as the first stream stops.Internal streamlyLike  ? but stops the output as soon as any of the two streams stops.Internal streamlyGenerate a stream asynchronously to keep it buffered, lazily consume from the buffer.Internal streamlyRedirect a copy of the stream to a supplied fold and run it concurrently in an independent thread. The fold may buffer some elements. The buffer size is determined by the prevailing  maxBuffer setting.  Stream m a -> m b | -----stream m a ---------------stream m a-----  > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2) 1 2 Exceptions from the concurrently running fold are propagated to the current computation. Note that, because of buffering in the fold, exceptions may be delayed and may not correspond to the current element being processed in the parent stream, but we guarantee that before the parent stream stops the tap finishes and all exceptions from it are drained. Compare with tap.Internal streamlyConcurrently distribute a stream to a collection of fold functions, discarding the outputs of the folds.S.drain $ distributeAsync_ [S.mapM_ print, S.mapM_ print] (S.enumerateFromTo 1 2) )distributeAsync_ = flip (foldr tapAsync) Internal streamly(Fix the type of a polymorphic stream as  . *(c) 2018 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone streamlyTypes that can be enumerated as a stream. The operations in this type class are equivalent to those in the  type class, except that these generate a stream instead of a list. Use the functions in )Streamly.Internal.Data.Stream.Enumeration module to define new instances. streamlyenumerateFrom from/ generates a stream starting with the element from, enumerating up to  when the type is 8 or generating an infinite stream when the type is not . => S.toList $ S.take 4 $ S.enumerateFrom (0 :: Int) [0,1,2,3] For   types, enumeration is numerically stable. However, no overflow or underflow checks are performed. >> S.toList $ S.take 4 $ S.enumerateFrom 1.1 [1.1,2.1,3.1,4.1] streamly3Generate a finite stream starting with the element from(, enumerating the type up to the value to. If to is smaller than from# then an empty stream is returned. /> S.toList $ S.enumerateFromTo 0 4 [0,1,2,3,4] For  3 types, the last element is equal to the specified to5 value after rounding to the nearest integral value. > S.toList $ S.enumerateFromTo 1.1 4 [1.1,2.1,3.1,4.1] > S.toList $ S.enumerateFromTo 1.1 4.6 [1.1,2.1,3.1,4.1,5.1] streamlyenumerateFromThen from then, generates a stream whose first element is from, the second element is then3 and the successive elements are in increments of  then - from. Enumeration can occur downwards or upwards depending on whether then comes before or after from. For  types the stream ends when  is reached, for unbounded types it keeps enumerating infinitely. > S.toList $ S.take 4 $ S.enumerateFromThen 0 2 [0,2,4,6] > S.toList $ S.take 4 $ S.enumerateFromThen 0 (-2) [0,-2,-4,-6] streamly enumerateFromThenTo from then to3 generates a finite stream whose first element is from, the second element is then3 and the successive elements are in increments of  then - from up to to. Enumeration can occur downwards or upwards depending on whether then comes before or after from. > S.toList $ S.enumerateFromThenTo 0 2 6 [0,2,4,6] > S.toList $ S.enumerateFromThenTo 0 (-2) (-6) [0,-2,-4,-6] streamly#enumerateFromStepIntegral from step6 generates an infinite stream whose first element is from3 and the successive elements are in increments of step.CAUTION: This function is not safe for finite integral types. It does not check for overflow, underflow or bounds. > S.toList $ S.take 4 $ S.enumerateFromStepIntegral 0 2 [0,2,4,6] > S.toList $ S.take 3 $ S.enumerateFromStepIntegral 0 (-2) [0,-2,-4] streamly Enumerate an  type. enumerateFromIntegral from, generates a stream whose first element is from3 and the successive elements are in increments of 1+. The stream is bounded by the size of the  type. > S.toList $ S.take 4 $ S.enumerateFromIntegral (0 :: Int) [0,1,2,3] streamly Enumerate an  type in steps. $enumerateFromThenIntegral from then+ generates a stream whose first element is from, the second element is then2 and the successive elements are in increments of  then - from,. The stream is bounded by the size of the  type. > S.toList $ S.take 4 $ S.enumerateFromThenIntegral (0 :: Int) 2 [0,2,4,6] > S.toList $ S.take 4 $ S.enumerateFromThenIntegral (0 :: Int) (-2) [0,-2,-4,-6] streamly Enumerate an  type up to a given limit. enumerateFromToIntegral from to3 generates a finite stream whose first element is from. and successive elements are in increments of 1 up to to. 7> S.toList $ S.enumerateFromToIntegral 0 4 [0,1,2,3,4] streamly Enumerate an % type in steps up to a given limit. (enumerateFromThenToIntegral from then to3 generates a finite stream whose first element is from, the second element is then3 and the successive elements are in increments of  then - from up to to. > S.toList $ S.enumerateFromThenToIntegral 0 2 6 [0,2,4,6] > S.toList $ S.enumerateFromThenToIntegral 0 (-2) (-6) [0,-2,-4,-6] streamly&Numerically stable enumeration from a   number in steps of size 1. enumerateFromFractional from, generates a stream whose first element is from2 and the successive elements are in increments of 12. No overflow or underflow checks are performed.This is the equivalent to  for   types. For example: > S.toList $ S.take 4 $ S.enumerateFromFractional 1.1 [1.1,2.1,3.1,4.1] streamly&Numerically stable enumeration from a   number in steps. %enumerateFromThenFractional from then, generates a stream whose first element is from, the second element is then3 and the successive elements are in increments of  then - from2. No overflow or underflow checks are performed.This is the equivalent of  for   types. For example: > S.toList $ S.take 4 $ S.enumerateFromThenFractional 1.1 2.1 [1.1,2.1,3.1,4.1] > S.toList $ S.take 4 $ S.enumerateFromThenFractional 1.1 (-2.1) [1.1,-2.1,-5.300000000000001,-8.500000000000002] streamly&Numerically stable enumeration from a   number to a given limit. !enumerateFromToFractional from to3 generates a finite stream whose first element is from. and successive elements are in increments of 1 up to to.This is the equivalent of  for   types. For example: > S.toList $ S.enumerateFromToFractional 1.1 4 [1.1,2.1,3.1,4.1] > S.toList $ S.enumerateFromToFractional 1.1 4.6 [1.1,2.1,3.1,4.1,5.1] 7Notice that the last element is equal to the specified to. value after rounding to the nearest integer. streamly&Numerically stable enumeration from a  ( number in steps up to a given limit. *enumerateFromThenToFractional from then to3 generates a finite stream whose first element is from, the second element is then3 and the successive elements are in increments of  then - from up to to.This is the equivalent of  for   types. For example: > S.toList $ S.enumerateFromThenToFractional 0.1 2 6 [0.1,2.0,3.9,5.799999999999999] > S.toList $ S.enumerateFromThenToFractional 0.1 (-2) (-6) [0.1,-2.0,-4.1000000000000005,-6.200000000000001] streamly  for  types not larger than  . streamly  for  types not larger than  . streamly  for  types not larger than  .Note: We convert the  to   and enumerate the  ,. If a type is bounded but does not have a  instance then we can go on enumerating it beyond the legal values of the type, resulting in the failure of  when converting back to . Therefore we require a / instance for this function to be safely used. streamly "enumerate = enumerateFrom minBound Enumerate a  type from its  to  streamly &enumerateTo = enumerateFromTo minBound Enumerate a  type from its  to specified value. streamly 4enumerateFromBounded = enumerateFromTo from maxBound  for   types.  +(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone#$? streamlyDecompose a stream into its head and tail. If the stream is empty, returns &. If the stream is non-empty, returns  Just (a, ma), where a is the head of the stream and ma its tail.This is a brute force primitive. Avoid using it as long as possible, use it when no other combinator can do the job. This can be used to do pretty much anything in an imperative manner, as it just breaks down the stream into individual elements and we can loop over them as we deem fit. For example, this can be used to convert a streamly stream into other stream types. streamly 7unfoldr step s = case step s of Nothing -> 0 Just (a, b) -> a `cons` unfoldr step b Build a stream by unfolding a pure step function step starting from a seed s. The step function returns the next element in the stream and the next seed value. When it is done it returns # and the stream ends. For example, let f b = if b > 3 then Nothing else Just (b, b + 1) in toList $ unfoldr f 0  [0,1,2,3] streamlyBuild a stream by unfolding a monadic step function starting from a seed. The step function returns the next element in the stream and the next seed value. When it is done it returns # and the stream ends. For example, let f b = if b > 3 then return Nothing else print b >> return (Just (b, b + 1)) in drain $ unfoldrM f 0   0 1 2 3 When run concurrently, the next unfold step can run concurrently with the processing of the output of the previous step. Note that more than one step cannot run concurrently as the next step depends on the output of the previous step. (asyncly $ S.unfoldrM (\n -> liftIO (threadDelay 1000000) >> return (Just (n, n + 1))) 0) & S.foldlM' (\_ a -> threadDelay 1000000 >> print a) ()  Concurrent Since: 0.1.0 streamly Convert an - into a stream by supplying it an input seed.,unfold (UF.replicateM 10) (putStrLn "hello") Since: 0.7.0 streamly yield a = a `cons` nil ,Create a singleton stream from a pure value.?The following holds in monadic streams, but not in Zip streams: #yield = pure yield = yieldM . pure In Zip applicative streams   is not the same as   because in that case   is equivalent to   instead.   and  ( are equally efficient, in other cases   may be slightly more efficient than the other equivalent definitions. streamly yieldM m = m `consM` nil 0Create a singleton stream from a monadic action. *> toList $ yieldM getLine hello ["hello"] streamly 6fromIndices f = let g i = f i `cons` g (i + 1) in g 0 Generate an infinite stream, whose values are the output of a function f9 applied on the corresponding index. Index starts at 0. 5> S.toList $ S.take 5 $ S.fromIndices id [0,1,2,3,4] streamly 8fromIndicesM f = let g i = f i `consM` g (i + 1) in g 0 Generate an infinite stream, whose values are the output of a monadic function f7 applied on the corresponding index. Index starts at 0. Concurrent streamly replicateM = take n . repeatM 1Generate a stream by performing a monadic action n times. Same as: drain $ serially $ S.replicateM 10 $ (threadDelay 1000000 >> print 1) drain $ asyncly $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)  Concurrent streamly replicate = take n . repeat Generate a stream of length n by repeating a value n times. streamly6Generate an infinite stream by repeating a pure value. streamly 0repeatM = fix . consM repeatM = cycle1 . yieldM Generate a stream by repeatedly executing a monadic action forever. drain $ serially $ S.take 10 $ S.repeatM $ (threadDelay 1000000 >> print 1) drain $ asyncly $ S.take 10 $ S.repeatM $ (threadDelay 1000000 >> print 1) &Concurrent, infinite (do not use with  parallely) streamly #iterate f x = x `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. 5> S.toList $ S.take 5 $ S.iterate (+1) 1 [1,2,3,4,5] streamly >= a -> return a `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.When run concurrently, the next iteration can run concurrently with the processing of the previous iteration. Note that more than one iteration cannot run concurrently as the next iteration depends on the output of the previous iteration. drain $ serially $ S.take 10 $ S.iterateM (\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0) drain $ asyncly $ S.take 10 $ S.iterateM (\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)  ConcurrentSince: 0.7.0 (signature change) Since: 0.1.2 streamly  fromListM =     Construct a stream from a list of monadic actions. This is more efficient than   for serial streams. streamly fromFoldableM =     Construct a stream from a   containing monadic actions. drain $ serially $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1) drain $ asyncly $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1) Concurrent (do not use with  parallely on infinite containers) streamlySame as  fromFoldable. streamly6Read lines from an IO Handle into a stream of Strings. streamly Construct a stream by reading a   repeatedly.Internal streamlyTakes a callback setter function and provides it with a callback. The callback when invoked adds a value at the tail of the stream. Returns a stream of values generated by the callback.Internal streamly currentTime g returns a stream of absolute timestamps using a clock of granularity g specified in seconds. A low granularity clock is more expensive in terms of CPU usage..Note: This API is not safe on 32-bit machines.Internal streamly"Right associative/lazy pull fold. foldrM build final stream9 constructs an output structure using the step function build. build is invoked with the next input element and the remaining (lazy) tail of the output structure. It builds a lazy output expression using the two. When the "tail structure" in the output expression is evaluated it calls build( again thus lazily consuming the input stream. until either the output expression built by build is free of the "tail" or the input is exhausted in which case final is used as the terminating case for the output structure. For more details see the description in the previous section.%Example, determine if any element is  in a stream:S.foldrM (\x xs -> if odd x then return True else xs) (return False) $ S.fromList (2:4:5:undefined)> True Since: 0.7.0 (signature changed) Since: 0.2.0 (signature changed) Since: 0.1.0 streamly Right fold to a streaming monad. foldrS S.cons S.nil === id  can be used to perform stateless stream to stream transformations like map and filter in general. It can be coupled with a scan to perform stateful transformations. However, note that the custom map and filter routines can be much more efficient than this due to better stream fusion.4S.toList $ S.foldrS S.cons S.nil $ S.fromList [1..5] > [1,2,3,4,5]%Find if any element in the stream is :S.toList $ S.foldrS (\x xs -> if odd x then return True else xs) (return False) $ (S.fromList (2:4:5:undefined) :: SerialT IO Int)> [True]:Map (+2) on odd elements and filter out the even elements:S.toList $ S.foldrS (\x xs -> if odd x then (x + 2) `S.cons` xs else xs) S.nil $ (S.fromList [1..5] :: SerialT IO Int) > [3,5,7] % can also be represented in terms of  ., however, the former is much more efficient: foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) sInternal streamlyRight fold to a transformer monad. This is the most general right fold function.   is a special case of   , however  ' implementation can be more efficient: foldrS = foldrT foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s  can be used to translate streamly streams to other transformer monads e.g. to a different streaming type.Internal streamlyRight fold, lazy for lazy monads and pure streams, and strict for strict monads.Please avoid using this routine in strict monads like IO unless you need a strict right fold. This is provided only for use in lazy monads (e.g. Identity) or pure streams. Note that with this signature it is not possible to implement a lazy foldr when the monad m is strict. In that case it would be strict in its accumulator and therefore would necessarily consume all its input. streamlyLazy right fold for non-empty streams, using first element as the starting value. Returns  if the stream is empty. streamlyStrict left fold with an extraction function. Like the standard strict left fold, but applies a user supplied extraction function (the third argument) to the folded value at the end. This is designed to work with the foldl library. The suffix x is a mnemonic for extraction. streamly#Left associative/strict push fold. foldl' reduce initial stream invokes reduce with the accumulator and the next input in the input stream, using initial as the initial value of the current value of the accumulator. When the input is exhausted the current value of the accumulator is returned. Make sure to use a strict data structure for accumulator to not build unnecessary lazy expressions unless that's what you want. See the previous section for more details. streamlyStrict left fold, for non-empty streams, using first element as the starting value. Returns  if the stream is empty. streamlyLike  #, but with a monadic step function. streamlyLike  " but with a monadic step function. streamly+Fold a stream using the supplied left fold.'S.fold FL.sum (S.enumerateFromTo 1 100)5050 streamly"Parse a stream using the supplied Parse.Internal streamly drain = mapM_ (\_ -> return ())Run a stream, discarding the results. By default it interprets the stream as , to run other types of streams use the type adapting combinators for example drain . asyncly. streamlyRun a stream, discarding the results. By default it interprets the stream as , to run other types of streams use the type adapting combinators for example  runStream . asyncly. streamly drainN n = drain . take nRun maximum up to n iterations of a stream. streamly runN n = runStream . take nRun maximum up to n iterations of a stream. streamly "drainWhile p = drain . takeWhile p1Run a stream as long as the predicate holds true. streamly $runWhile p = runStream . takeWhile p1Run a stream as long as the predicate holds true. streamly&Determine whether the stream is empty. streamly0Extract the first element of the stream, if any.  head = (!! 0) streamlyExtract the first element of the stream, if any, otherwise use the supplied default value. It can help avoid one branch in high performance code.Internal streamly tail = fmap (fmap snd) . uncons8Extract all but the first element of the stream, if any. streamly7Extract all but the last element of the stream, if any. streamly/Extract the last element of the stream, if any. last xs = xs !! (length xs - 1) streamly6Determine whether an element is present in the stream. streamly:Determine whether an element is not present in the stream. streamly#Determine the length of the stream. streamly?Determine whether all elements of a stream satisfy a predicate. streamlyDetermine whether any of the elements of a stream satisfy a predicate. streamly8Determines if all elements of a boolean stream are True. streamlyDetermines whether at least one element of a boolean stream is True. streamlyDetermine the sum of all elements of a stream of numbers. Returns 0 when the stream is empty. Note that this is not numerically stable for floating point numbers. streamlyDetermine the product of all elements of a stream of numbers. Returns 1 when the stream is empty. streamly3Fold a stream of monoid elements by appending them.Internal streamly  minimum =   compare *Determine the minimum element in a stream. streamlyDetermine the minimum element in a stream using the supplied comparison function. streamly  maximum =   compare *Determine the maximum element in a stream. streamlyDetermine the maximum element in a stream using the supplied comparison function. streamly&Lookup the element at the given index. streamly!In a stream of (key-value) pairs (a, b), return the value b9 of the first pair where the key equals the given value a. "lookup = snd <$> find ((==) . fst) streamlyLike  " but with a non-monadic predicate. find p = findM (return . p) streamly=Returns the first element that satisfies the given predicate. streamlyFind all the indices where the element in the stream satisfies the given predicate. streamly;Returns the first index that satisfies the given predicate. streamlyFind all the indices where the value of the element in the stream is equal to the given value. streamlyReturns the first index where a given value is found in the stream. elemIndex a = findIndex (== a) streamlyReturns  if the first stream is the same as or a prefix of the second. A stream is a prefix of itself. > S.isPrefixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char) True streamlyReturns  if the first stream is a suffix of the second. A stream is considered a suffix of itself. > S.isSuffixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char) True Space: O(n)-, buffers entire input stream and the suffix.Internal Suboptimal - Help wanted. streamlyReturns  if the first stream is an infix of the second. A stream is considered an infix of itself. > S.isInfixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char) True Space: O(n) worst case where n is the length of the infix.Internal Requires  constraint - Help wanted. streamlyReturns  if all the elements of the first stream occur, in order, in the second stream. The elements do not have to occur consecutively. A stream is a subsequence of itself. > S.isSubsequenceOf (S.fromList "hlo") (S.fromList "hello" :: SerialT IO Char) True streamlyStrip prefix if present and tell whether it was stripped or not. Returns  if the stream does not start with the given prefix, stripped stream otherwise. Returns Just nil, when the prefix is the same as the stream.Space: O(1) streamly.Drops the given suffix from a stream. Returns < if the stream does not end with the given suffix. Returns Just nil, when the suffix is the same as the stream.It may be more efficient to convert the stream to an Array and use stripSuffix on that especially if the elements have a Storable or Prim instance.Space: O(n)7, buffers the entire input stream as well as the suffixInternal streamly-Drop prefix from the input stream if present.Space: O(1) Unimplemented - Help wanted. streamlyDrop all matching infix from the input stream if present. Infix stream may be consumed multiple times.Space: O(n)$ where n is the length of the infix. Unimplemented - Help wanted. streamlyDrop suffix from the input stream if present. Suffix stream may be consumed multiple times.Space: O(n)% where n is the length of the suffix. Unimplemented - Help wanted. streamly mapM_ = drain . mapMApply a monadic action to each element of the stream and discard the output of the action. This is not really a pure transformation operation but a transformation followed by fold. streamly toList = S.foldr (:) [] Convert a stream into a list in the underlying monad. The list can be consumed lazily in a lazy monad (e.g.  ). In a strict monad (e.g. IO) the whole list is generated and buffered before it can be consumed.Warning! working on large lists accumulated as buffers in memory could be very inefficient, consider using Streamly.Array instead. streamly #toListRev = S.foldl' (flip (:)) [] Convert a stream into a list in reverse order in the underlying monad.Warning! working on large lists accumulated as buffers in memory could be very inefficient, consider using Streamly.Array instead.Internal streamly #toHandle h = S.mapM_ $ hPutStrLn h *Write a stream of Strings to an IO Handle. streamly/A fold that buffers its input to a pure stream.Warning! working on large streams accumulated as buffers in memory could be very inefficient, consider using Streamly.Array instead.Internal streamlyBuffers the input stream to a pure stream in the reverse order of the input.Warning! working on large streams accumulated as buffers in memory could be very inefficient, consider using Streamly.Array instead.Internal streamly"Convert a stream to a pure stream. toPure = foldr cons nil Internal streamly3Convert a stream to a pure stream in reverse order. #toPureRev = foldl' (flip cons) nil Internal streamlyParallel transform application operator; applies a stream transformation function t m a -> t m b to a stream t m a concurrently; the input stream is evaluated asynchronously in an independent thread yielding elements to a buffer and the transformation function runs in another thread consuming the input from the buffer.  5 is just like regular function application operator  except that it is concurrent.If you read the signature as $(t m a -> t m b) -> (t m a -> t m b) you can look at it as a transformation that converts a transform function to a buffered concurrent transform function.The following code prints a value every second even though each stage adds a 1 second delay. drain $ S.mapM (\x -> threadDelay 1000000 >> print x) |$ S.repeatM (threadDelay 1000000 >> return 1)  Concurrent streamlySame as  .Internal streamlyParallel reverse function application operator for streams; just like the regular reverse function application operator & except that it is concurrent. drain $ S.repeatM (threadDelay 1000000 >> return 1) |& S.mapM (\x -> threadDelay 1000000 >> print x)  Concurrent streamly m b to a stream t m a concurrently; The the input stream is evaluated asynchronously in an independent thread yielding elements to a buffer and the folding action runs in another thread consuming the input from the buffer.If you read the signature as  (t m a -> m b) -> (t m a -> m b) you can look at it as a transformation that converts a fold function to a buffered concurrent fold function.The . at the end of the operator is a mnemonic for termination of the stream.  S.foldlM' (\_ a -> threadDelay 1000000 >> print a) () |$. S.repeatM (threadDelay 1000000 >> return 1)  Concurrent streamlySame as  .Internal streamlyParallel reverse function application operator for applying a run or fold functions to a stream. Just like  ' except that the operands are reversed.  S.repeatM (threadDelay 1000000 >> return 1) |&. S.foldlM' (\_ a -> threadDelay 1000000 >> print a) ()  Concurrent streamlyUse a | to transform a stream.Internal streamly3Strict left scan with an extraction function. Like  , but applies a user supplied extraction function (the third argument) at each step. This is designed to work with the foldl library. The suffix x is a mnemonic for extraction.!Since: 0.7.0 (Monad m constraint) Since 0.2.0 streamlyLike  " but with a monadic fold function. streamlyStrict left scan. Like map,   too is a one to one transformation, however it adds an extra element. >> S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4] [0,1,3,6,10]  > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4] [[],[1],[2,1],[3,2,1],[4,3,2,1]] The output of   is the initial value of the accumulator followed by all the intermediate steps and the final result of  .By streaming the accumulated state after each fold step, we can share the state across multiple stages of stream composition. Each stage can modify or extend the state, do some processing with it and emit it for the next stage, thus modularizing the stream processing. This can be useful in stateful or event-driven programming.Consider the following monolithic example, computing the sum and the product of the elements in a stream in one go using a foldl': > S.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList [1,2,3,4] (10,24) Using scanl' we can make it modular by computing the sum in the first stage and passing it down to the next stage for computing the product: > S.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1) $ S.scanl' (\(s, _) x -> (s + x, x)) (0,1) $ S.fromList [1,2,3,4] (10,24)  IMPORTANT:   evaluates the accumulator to WHNF. To avoid building lazy expressions inside the accumulator, it is recommended that a strict data structure is used for accumulator. streamlyLike  : but does not stream the initial value of the accumulator. .postscanl' f z xs = S.drop 1 $ S.scanl' f z xs streamlyLike  " but with a monadic step function. streamlyLike scanl' but does not stream the final value of the accumulator.Internal streamly1Like postscanl' but with a monadic step function.Internal streamlyLike  " but with a monadic step function. streamlyLike   but for a non-empty stream. The first element of the stream is used as the initial value of the accumulator. Does nothing if the stream is empty. :> S.toList $ S.scanl1 (+) $ fromList [1,2,3,4] [1,3,6,10] streamly+Scan a stream using the given monadic fold. streamly/Postscan a stream using the given monadic fold. streamlyApply a function on every two successive elements of a stream. If the stream consists of a single element the output is an empty stream.Internal streamlyLike  $ but with an effectful map function.Internal streamly2Include only those elements that pass a predicate. streamlySame as   but with a monadic predicate. streamly7Drop repeated elements that are adjacent to each other. streamlyEnsures that all the elements of the stream are identical and then returns that unique element. streamly Take first n/ elements from the stream and discard the rest. streamly drain $ S.mapM putStr $ S.fromList ["a", "b", "c"] abc drain $ S.replicateM 10 (return 1) & (serially . S.mapM (\x -> threadDelay 1000000 >> print x)) drain $ S.replicateM 10 (return 1) & (asyncly . S.mapM (\x -> threadDelay 1000000 >> print x)) Concurrent (do not use with  parallely on infinite streams) streamly sequence = mapM id Replace the elements of a stream of monadic actions with the outputs of those actions. > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"] abc drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1) & (serially . S.sequence) drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1) & (asyncly . S.sequence) Concurrent (do not use with  parallely on infinite streams) streamlyMap a  0 returning function to a stream, filter out the 9 elements, and return a stream of values extracted from  .Equivalent to: mapMaybe f = S.map  . S.filter  . S.map f streamlyLike   but maps a monadic function.Equivalent to: mapMaybeM f = S.map  . S.filter  . S.mapM f Concurrent (do not use with  parallely on infinite streams) streamlyReturns the elements of the stream in reverse order. The stream must be finite. Note that this necessarily buffers the entire stream in memory. Since 0.7.0 (Monad m constraint) Since: 0.1.1 streamlyLike  & but several times faster, requires a  instance.Internal streamlyGenerate a stream by inserting the result of a monadic action between consecutive elements of the given stream. Note that the monadic action is performed after the stream action before which its result is inserted. > S.toList $ S.intersperseM (return ',') $ S.fromList "hello" "h,e,l,l,o" streamlyGenerate a stream by inserting a given element between consecutive elements of the given stream. > S.toList $ S.intersperse ',' $ S.fromList "hello" "h,e,l,l,o" streamly9Insert a monadic action after each element in the stream.Internal streamlyIntroduces a delay of specified seconds after each element of a stream.Internal streamlyLike   but intersperses a monadic action into the input stream after every n% elements and after the last element. > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello" "he,ll,o," Internal streamly?Intersperse a monadic action into the input stream after every n seconds. > S.drain $ S.interjectSuffix 1 (putChar ',') $ S.mapM (\x -> threadDelay 1000000 >> putChar x) $ S.fromList "hello" "h,e,l,l,o" Internal streamlyinsertBy cmp elem stream inserts elem before the first element in stream that is less than elem when compared using cmp. insertBy cmp x =   cmp (  x) > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5] [1,2,3,5] streamlyDeletes the first occurrence of the element in the stream that satisfies the given equality predicate. >> S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5] [1,3,5] streamly indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined) indexed = S.zipWith (,) (S.enumerateFrom 0)Pair each element in a stream with its index, starting from index 0. 0> S.toList $ S.indexed $ S.fromList "hello" [(0,h),(1,e),(2,l),(3,l),(4,o)] streamly indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined) indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))Pair each element in a stream with its index, starting from the given index n and counting down. 5> S.toList $ S.indexedR 10 $ S.fromList "hello" [(10,h),(9,e),(8,l),(7,l),(6,o)] streamly S.toList $ S.mergeBy compare (S.fromList [1,3,5]) (S.fromList [2,4,6,8]) [1,2,3,4,5,6,8] streamlyLike  ( but with a monadic comparison function.Merge two streams randomly: > randomly _ _ = randomIO >>= x -> return $ if x then LT else GT > S.toList $ S.mergeByM randomly (S.fromList [1,1,1,1]) (S.fromList [2,2,2,2]) [2,1,2,2,2,1,1,1] )Merge two streams in a proportion of 2:1: proportionately m n = do ref <- newIORef $ cycle $ concat [replicate m LT, replicate n GT] return $ \_ _ -> do r <- readIORef ref writeIORef ref $ tail r return $ head r main = do f <- proportionately 2 1 xs <- S.toList $ S.mergeByM f (S.fromList [1,1,1,1,1,1]) (S.fromList [2,2,2]) print xs [1,1,2,1,1,2,1,1,2] streamlyLike   but merges concurrently (i.e. both the elements being merged are generated concurrently). streamlyLike   but merges concurrently (i.e. both the elements being merged are generated concurrently). streamlyconcatMapWith merge map stream is a two dimensional looping combinator. The first argument specifies a merge or concat function that is used to merge the streams generated by applying the second argument i.e. the map function to each element of the input stream. The concat function could be serial, parallel, async, ahead or any other zip or merge function and the second argument could be any stream generation function using a seed.Compare  streamlyMap a stream producing function on each element of the stream and then flatten the results into a single stream.  concatMap =    concatMap f =   (return . f) streamly/Flatten a stream of streams to a single stream. concat = concatMap id Internal streamlyAppend the outputs of two streams, yielding all the elements from the first stream and then yielding all the elements from the second stream./IMPORTANT NOTE: This could be 100x faster than  serial/<> for appending a few (say 100) streams because it can fuse via stream fusion. However, it does not scale for a large number of streams (say 1000s) and becomes qudartically slow. Therefore use this for custom appending of a few streams but use  ) or 'concatMapWith serial' for appending n, streams or infinite containers of streams.Internal streamlyInterleaves the outputs of two streams, yielding elements from each stream alternately, starting from the first stream. If any of the streams finishes early the other stream continues alone until it too finishes.:set -XOverloadedStrings/interleave "ab" ",,,," :: SerialT Identity CharfromList "a,b,,,"/interleave "abcd" ",," :: SerialT Identity CharfromList "a,b,cd"  is dual to  , it can be called  interleaveMax.%Do not use at scale in concatMapWith.Internal streamlyInterleaves the outputs of two streams, yielding elements from each stream alternately, starting from the first stream. As soon as the first stream finishes, the output stops, discarding the remaining part of the second stream. In this case, the last element in the resulting stream would be from the second stream. If the second stream finishes early then the first stream still continues to yield elements until it finishes.:set -XOverloadedStrings6interleaveSuffix "abc" ",,,," :: SerialT Identity CharfromList "a,b,c,"3interleaveSuffix "abc" "," :: SerialT Identity CharfromList "a,bc"  is a dual of  .%Do not use at scale in concatMapWith.Internal streamlyInterleaves the outputs of two streams, yielding elements from each stream alternately, starting from the first stream and ending at the first stream. If the second stream is longer than the first, elements from the second stream are infixed with elements from the first stream. If the first stream is longer then it continues yielding elements even after the second stream has finished.:set -XOverloadedStrings5interleaveInfix "abc" ",,,," :: SerialT Identity CharfromList "a,b,c"2interleaveInfix "abc" "," :: SerialT Identity CharfromList "a,bc"  is a dual of  .%Do not use at scale in concatMapWith.Internal streamlyInterleaves the outputs of two streams, yielding elements from each stream alternately, starting from the first stream. The output stops as soon as any of the two streams finishes, discarding the remaining part of the other stream. The last element of the resulting stream would be from the longer stream.:set -XOverloadedStrings2interleaveMin "ab" ",,,," :: SerialT Identity CharfromList "a,b,"2interleaveMin "abcd" ",," :: SerialT Identity CharfromList "a,b,c"  is dual to  .%Do not use at scale in concatMapWith.Internal streamlySchedule the execution of two streams in a fair round-robin manner, executing each stream once, alternately. Execution of a stream may not necessarily result in an output, a stream may chose to Skip producing an element until later giving the other stream a chance to run. Therefore, this combinator fairly interleaves the execution of two streams rather than fairly interleaving the output of the two streams. This can be useful in co-operative multitasking without using explicit threads. This can be used as an alternative to async.%Do not use at scale in concatMapWith.Internal streamlyMap a stream producing monadic function on each element of the stream and then flatten the results into a single stream. Since the stream generation function is monadic, unlike  , it can produce an effect at the beginning of each iteration of the inner loop. streamlyGiven a stream value in the underlying monad, lift and join the underlying monad with the stream monad. Compare with   and  .Internal streamlyLike   but uses an  for stream generation. Unlike   this can fuse the  code with the inner loop and therefore provide many times better performance. streamlyLike  1 but interleaves the streams in the same way as  # behaves instead of appending them.Internal streamlyLike  . but executes the streams in the same way as  .Internal streamly  followed by unfold and concat.Internal streamly  followed by unfold and concat. %unwords = intercalate " " UF.fromList1intercalate " " UF.fromList ["abc", "def", "ghi"]> "abc def ghi"Internal streamlyUnfold the elements of a stream, intersperse the given element between the unfolded streams and then concat them into a single stream. unwords = S.interpose ' 'Internal streamly  followed by unfold and concat.Internal streamly  followed by unfold and concat. ,unlines = intercalateSuffix "\n" UF.fromList2intercalate "\n" UF.fromList ["abc", "def", "ghi"]> "abc\ndef\nghi\n"Internal streamlyUnfold the elements of a stream, append the given element after each unfolded stream and then concat them into a single stream.  unlines = S.interposeSuffix '\n'Internal streamlyLike  ' but using a stream generator function.Internal streamlyTraverse a forest with recursive tree structures whose non-leaf nodes are of type a and leaf nodes are of type b, flattening all the trees into streams and combining the streams into a single stream consisting of both leaf and non-leaf nodes.  is a generalization of  , using a recursive feedback loop to append the non-leaf nodes back to the input stream enabling recursive traversal.  * flattens a single level nesting whereas  ) flattens a recursively nested structure.Traversing a directory tree recursively is a canonical use case of  . concatMapTreeWith combine f xs = concatMapIterateWith combine g xs where g (Left tree) = f tree g (Right leaf) = nil Internal streamly:Flatten a stream with a feedback loop back into the input.For example, exceptions generated by the output stream can be fed back to the input to take any corrective action. The corrective action may be to retry the action or do nothing or log the errors. For the retry case we need a feedback loop.Internal streamly1Concat a stream of trees, generating only leaves. Compare with  . While the latter returns all nodes in the tree, this one returns only the leaves.Traversing a directory tree recursively and yielding on the files is a canonical use case of  . concatMapTreeYieldLeavesWith combine f = concatMapLoopWith combine f yield Internal streamlyApply a Parse repeatedly on a stream and emit the parsed values in the output stream.S.toList $ S.splitParse (PR.take 2 $ PR.fromFold FL.sum) $ S.fromList [1..10]> [3,7,11,15,19]S.toList $ S.splitParse (PR.line FL.toList) $ S.fromList "hello\nworld"> ["hello\n","world"] streamly&Group the input stream into groups of n elements each and then fold each group using the provided fold function. > S.toList $ S.chunksOf 2 FL.sum (S.enumerateFromTo 1 10) [3,7,11,15,19]/This can be considered as an n-fold version of ltake where we apply ltake= repeatedly on the leftover stream until the stream exhausts. streamlyInternal streamlyarraysOf n stream9 groups the elements in the input stream into arrays of n elements each.0Same as the following but may be more efficient: &arraysOf n = S.chunksOf n (A.writeN n)Internal streamly'Group the input stream into windows of n second each and then fold each group using the provided fold function. streamly'groupsBy cmp f $ S.fromList [a,b,c,...] assigns the element a to the first group, if  a `cmp` b is  then b* is also assigned to the same group. If  a `cmp` c is  then c is also assigned to the same group and so on. When the comparison fails a new group is started. Each group is folded using the fold f= and the result of the fold is emitted in the output stream.>S.toList $ S.groupsBy (>) FL.toList $ S.fromList [1,3,7,0,2,5]> [[1,3,7],[0,2,5]] streamlyUnlike groupsBy this function performs a rolling comparison of two successive elements in the input stream. /groupsByRolling cmp f $ S.fromList [a,b,c,...] assigns the element a to the first group, if  a `cmp` b is  then b) is also assigned to the same group. If  b `cmp` c is  then c is also assigned to the same group and so on. When the comparison fails a new group is started. Each group is folded using the fold f.S.toList $ S.groupsByRolling (\a b -> a + 1 == b) FL.toList $ S.fromList [1,2,3,7,8,9]> [[1,2,3],[7,8,9]] streamly 4groups = groupsBy (==) groups = groupsByRolling (==)Groups contiguous spans of equal elements together in individual groups.4S.toList $ S.groups FL.toList $ S.fromList [1,1,2,2]> [[1,1],[2,2]] streamlySplit on an infixed separator element, dropping the separator. Splits the stream on separator elements determined by the supplied predicate, separator is considered as infixed between two segments, if one side of the separator is missing then it is parsed as an empty stream. The supplied ) is applied on the split segments. With * representing non-separator elements and  as separator,   splits as follows: ="--.--" => "--" "--" "--." => "--" "" ".--" => "" "--" splitOn (== x) is an inverse of intercalate (S.yield x)4Let's use the following definition for illustration: splitOn' p xs = S.toList $ S.splitOn p (FL.toList) (S.fromList xs)splitOn' (== '.') ""[""]splitOn' (== '.') "."["",""]splitOn' (== '.') ".a" > ["","a"]splitOn' (== '.') "a." > ["a",""]splitOn' (== '.') "a.b" > ["a","b"]splitOn' (== '.') "a..b"> ["a","","b"] streamlyLike   but the separator is considered as suffixed to the segments in the stream. A missing suffix at the end is allowed. A separator at the beginning is parsed as empty segment. With  representing elements and  as separator,   splits as follows:  "--.--." => "--" "--" "--.--" => "--" "--" ".--." => "" "--"  splitOnSuffix' p xs = S.toList $ S.splitSuffixBy p (FL.toList) (S.fromList xs)splitOnSuffix' (== '.') ""[]splitOnSuffix' (== '.') "."[""]splitOnSuffix' (== '.') "a"["a"]splitOnSuffix' (== '.') ".a" > ["","a"]splitOnSuffix' (== '.') "a."> ["a"]splitOnSuffix' (== '.') "a.b" > ["a","b"]splitOnSuffix' (== '.') "a.b." > ["a","b"] splitOnSuffix' (== '.') "a..b.."> ["a","","b",""] lines = splitOnSuffix (== '\n') streamlyLike   after stripping leading, trailing, and repeated separators. Therefore, ".a..b." with & as the separator would be parsed as  ["a","b"]. In other words, its like parsing words from whitespace separated text. wordsBy' p xs = S.toList $ S.wordsBy p (FL.toList) (S.fromList xs)wordsBy' (== ',') ""> []wordsBy' (== ',') ","> []wordsBy' (== ',') ",a,,b," > ["a","b"] words = wordsBy isSpace streamlyLike  8 but keeps the suffix attached to the resulting splits. splitWithSuffix' p xs = S.toList $ S.splitWithSuffix p (FL.toList) (S.fromList xs)splitWithSuffix' (== '.') ""[]splitWithSuffix' (== '.') "."["."]splitWithSuffix' (== '.') "a"["a"]splitWithSuffix' (== '.') ".a" > [".","a"]splitWithSuffix' (== '.') "a."> ["a."]splitWithSuffix' (== '.') "a.b" > ["a.","b"] splitWithSuffix' (== '.') "a.b." > ["a.","b."]"splitWithSuffix' (== '.') "a..b.."> ["a.",".","b.","."] streamlyLike   but the separator is a sequence of elements instead of a single element.For illustration, let's define a function that operates on pure lists: splitOnSeq' pat xs = S.toList $ S.splitOnSeq (A.fromList pat) (FL.toList) (S.fromList xs) splitOnSeq' "" "hello"> ["h","e","l","l","o"]splitOnSeq' "hello" ""> [""]splitOnSeq' "hello" "hello" > ["",""]splitOnSeq' "x" "hello" > ["hello"]splitOnSeq' "h" "hello" > ["","ello"]splitOnSeq' "o" "hello" > ["hell",""]splitOnSeq' "e" "hello" > ["h","llo"]splitOnSeq' "l" "hello"> ["he","","o"]splitOnSeq' "ll" "hello" > ["he","o"]  is an inverse of  !. The following law always holds: intercalate . splitOn == idThe following law holds when the separator is non-empty and contains none of the elements present in the input lists: splitOn . intercalate == idInternal streamlyLike  splitSuffixBy but the separator is a sequence of elements, instead of a predicate for a single element. splitSuffixOn_ pat xs = S.toList $ S.splitSuffixOn (A.fromList pat) (FL.toList) (S.fromList xs)splitSuffixOn_ "." ""[""]splitSuffixOn_ "." "."[""]splitSuffixOn_ "." "a"["a"]splitSuffixOn_ "." ".a" > ["","a"]splitSuffixOn_ "." "a."> ["a"]splitSuffixOn_ "." "a.b" > ["a","b"]splitSuffixOn_ "." "a.b." > ["a","b"]splitSuffixOn_ "." "a..b.."> ["a","","b",""] lines = splitSuffixOn "\n"Internal streamlyLike  5 but splits the separator as well, as an infix token. splitOn'_ pat xs = S.toList $ S.splitOn' (A.fromList pat) (FL.toList) (S.fromList xs)splitOn'_ "" "hello"#> ["h","","e","","l","","l","","o"]splitOn'_ "hello" ""> [""]splitOn'_ "hello" "hello"> ["","hello",""]splitOn'_ "x" "hello" > ["hello"]splitOn'_ "h" "hello"> ["","h","ello"]splitOn'_ "o" "hello"> ["hell","o",""]splitOn'_ "e" "hello"> ["h","e","llo"]splitOn'_ "l" "hello"> ["he","l","","l","o"]splitOn'_ "ll" "hello"> ["he","ll","o"]Internal streamlyLike  splitSuffixOn+ but keeps the suffix intact in the splits. splitSuffixOn'_ pat xs = S.toList $ FL.splitSuffixOn' (A.fromList pat) (FL.toList) (S.fromList xs)splitSuffixOn'_ "." ""[""]splitSuffixOn'_ "." "."["."]splitSuffixOn'_ "." "a"["a"]splitSuffixOn'_ "." ".a" > [".","a"]splitSuffixOn'_ "." "a."> ["a."]splitSuffixOn'_ "." "a.b" > ["a.","b"]splitSuffixOn'_ "." "a.b." > ["a.","b."]splitSuffixOn'_ "." "a..b.."> ["a.",".","b.","."]Internal streamly#splitInnerBy splitter joiner stream splits the inner containers f a of an input stream  t m (f a) using the splitter function. Container elements f a are collected until a split occurs, then all the elements before the split are joined using the joiner function.$For example, if we have a stream of  Array Word8, we may want to split the stream into arrays representing lines separated by 'n' byte such that the resulting stream after a split would be one array for each line.CAUTION! This is not a true streaming function as the container size after the split and merge may not be bounded.Internal streamlyLike   but splits assuming the separator joins the segment in a suffix style.Internal streamly-Tap the data flowing through a stream into a . For example, you may add a tap to log the contents flowing through the stream. The fold is used only for effects, its result is discarded.  Fold m a b | -----stream m a ---------------stream m a-----  > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2) 1 2  Compare with  . streamlytapOffsetEvery offset n taps every n&th element in the stream starting at offset. offset can be between 0 and n - 1. Offset 0 means start at the first element in the stream. If the offset is outside this range then offset  n is used as offset. >>> S.drain $ S.tapOffsetEvery 0 2 (FL.mapM print FL.toList) $ S.enumerateFromTo 0 10 > [0,2,4,6,8,10] Internal streamlyRedirect a copy of the stream to a supplied fold and run it concurrently in an independent thread. The fold may buffer some elements. The buffer size is determined by the prevailing  maxBuffer setting.  Stream m a -> m b | -----stream m a ---------------stream m a-----  > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2) 1 2 Exceptions from the concurrently running fold are propagated to the current computation. Note that, because of buffering in the fold, exceptions may be delayed and may not correspond to the current element being processed in the parent stream, but we guarantee that before the parent stream stops the tap finishes and all exceptions from it are drained. Compare with  .Internal streamly*pollCounts predicate transform fold stream4 counts those elements in the stream that pass the  predicate. The resulting count stream is sent to another thread which transforms it using  transform and then folds it using fold. The thread is automatically cleaned up if the stream stops or aborts due to exception.For example, to print the count of elements processed every second: > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print) $ S.enumerateFrom 0 5Note: This may not work correctly on 32-bit machines.Internal streamlyCalls the supplied function with the number of elements consumed every n seconds. The given function is run in a separate thread until the end of the stream. In case there is an exception in the stream the thread is killed during the next major GC.Note: The action is not guaranteed to run if the main thread exits. > delay n = threadDelay (round $ n * 1000000) >> return n > S.drain $ S.tapRate 2 (\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil) 2 elements processed 1 elements processed 5Note: This may not work correctly on 32-bit machines.Internal streamlyApply a monadic function to each element flowing through the stream and discard the results. 6> S.drain $ S.trace print (S.enumerateFromTo 1 2) 1 2  Compare with  . streamly2classifySessionsBy tick timeout idle pred f stream groups timestamped events in an input event stream into sessions based on a session key. Each element in the stream is an event consisting of a triple ((session key, sesssion data, timestamp).  session key is a key that uniquely identifies the session. All the events belonging to a session are folded using the fold f until the fold returns a  result or a timeout has occurred. The session key and the result of the fold are emitted in the output stream when the session is purged.When idle is , timeout is the maximum lifetime of a session in seconds, measured from the  timestamp+ of the first event in that session. When idle is  then the timeout is an idle timeout, it is reset after every event received in the session. timestamp in an event characterizes the time when the input event was generated, this is an absolute time measured from some Epoch. The notion of current time is maintained by a monotonic event time clock using the timestamps seen in the input stream. The latest timestamp seen till now is used as the base for the current time. When no new events are seen, a timer is started with a tick duration specified by tick. This timer is used to detect session timeouts in the absence of new events.The predicate pred; is invoked with the current session count, if it returns  a session is ejected from the session cache before inserting a new session. This could be useful to alert or eject sessions when the number of sessions becomes too high.Internal streamlyLike   but the session is kept alive if an event is received within the session window. The session times out and gets closed only if no event is received within the specified session window size."If the ejection predicate returns , the session that was idle for the longest time is ejected before inserting a new session. classifyKeepAliveSessions timeout pred = classifySessionsBy 1 timeout True pred Internal streamlySplit the stream into fixed size time windows of specified interval in seconds. Within each such window, fold the elements in sessions identified by the session keys. The fold result is emitted in the output stream if the fold returns a # result or if the time window ends.Session  timestamp in the input stream is an absolute time from some epoch, characterizing the time when the input element was generated. To detect session window end, a monotonic event time clock is maintained synced with the timestamps with a clock resolution of 1 second."If the ejection predicate returns , the session with the longest lifetime is ejected before inserting a new session. classifySessionsOf interval pred = classifySessionsBy 1 interval False pred Internal streamly=Run a side effect before the stream yields its first element. streamly5Run a side effect whenever the stream stops normally.Prefer   over this as the after action in this combinator is not executed if the unfold is partially evaluated lazily and then garbage collected. streamlyRun a side effect whenever the stream stops normally or is garbage collected after a partial lazy evaluation.Internal streamlyRun a side effect whenever the stream aborts due to an exception. streamlyRun a side effect whenever the stream stops normally or aborts due to an exception.Prefer   over this as the after action in this combinator is not executed if the unfold is partially evaluated lazily and then garbage collected. streamlyRun a side effect whenever the stream stops normally, aborts due to an exception or if it is garbage collected after a partial lazy evaluation.Internal streamlyRun the first action before the stream starts and remember its output, generate a stream using the output, run the second action using the remembered value as an argument whenever the stream ends normally or due to an exception.Prefer   over this as the after action in this combinator is not executed if the unfold is partially evaluated lazily and then garbage collected. streamlyRun the first action before the stream starts and remember its output, generate a stream using the output, run the second action using the remembered value as an argument whenever the stream ends normally, due to an exception or if it is garbage collected after a partial lazy evaluation.Internal streamlyWhen evaluating a stream if an exception occurs, stream evaluation aborts and the specified exception handler is run with the exception as argument. streamlyTransform the inner monad of a stream using a natural transformation. Internal streamly.Generalize the inner monad of the stream from   to any monad. Internal streamly;Lift the inner monad of a stream using a monad transformer. Internal streamly(Evaluate the inner monad of a stream as . Internal streamly(Evaluate the inner monad of a stream as .This is supported only for / as concurrent state updation may not be safe. Internal streamlyRun a stateful (StateT) stream transformation using a given state.This is supported only for / as concurrent state updation may not be safe. Internal streamly(Evaluate the inner monad of a stream as > and emit the resulting state and value pair after each step.This is supported only for / as concurrent state updation may not be safe. Internal streamly6Run a stream transformation using a given environment. Internal streamlyfeedback function to feed b back into input streamlytimer tick in secondsstreamlysession timeout in secondsstreamly+reset the timeout when an event is receivedstreamly2predicate to eject sessions based on session countstreamly$Fold to be applied to session eventsstreamlysession key, data, timestampstreamlysession key, fold result streamlysession inactive timeoutstreamly,predicate to eject sessions on session countstreamly*Fold to be applied to session payload datastreamlysession key, data, timestamp streamlytime window sizestreamly,predicate to eject sessions on session countstreamly$Fold to be applied to session eventsstreamlysession key, data, timestamp           0 1 0 1,!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone#$ streamly;Convert a stream of arrays into a stream of their elements.)Same as the following but more efficient: concat = S.concatMap A.read streamlyConvert a stream of arrays into a stream of their elements reversing the contents of each array before flattening. streamlyFlatten a stream of arrays after inserting the given element between arrays.Internal streamlyFlatten a stream of arrays appending the given element after each array. streamlySplit a stream of arrays on a given separator byte, dropping the separator and coalescing all the arrays between two separators into a single array. streamlyCoalesce adjacent arrays in incoming stream to form bigger arrays of a maximum specified size in bytes. streamlyarraysOf n stream9 groups the elements in the input stream into arrays of n elements each.)Same as the following but more efficient: &arraysOf n = S.chunksOf n (A.writeN n) streamlyGiven a stream of arrays, splice them all together to generate a single array. The stream must be finite. -!(c) 2018 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone  streamlyRead directories as Left and files as Right. Filter out "." and ".." entries.Internal streamlyRead files only.Internal streamly7Read directories only. Filter out "." and ".." entries.Internal streamlyRaw read of a directory.Internal streamlyRead directories as Left and files as Right. Filter out "." and ".." entries.Internal streamlyRead files only.Internal streamlyRead directories only.Internal  .(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone -0>?' streamlyA round robin parallely composing IO stream of elements of type a. See   documentation for more details. streamly  is similar to WSerialT% but with concurrent execution. The  operation (<>) for   merges two streams concurrently interleaving the actions from both the streams. In s1 <> s2 <> s3 ...&, the individual actions from streams s1, s2 and s3 are scheduled for execution in a round-robin fashion. Multiple scheduled actions may be executed concurrently, the results from concurrent executions are consumed in the order in which they become available.The W in the name stands for wide or breadth wise scheduling in contrast to the depth wise scheduling behavior of  . import Streamly import qualified Streamly.Prelude4 as S import Control.Concurrent main = (S.toList .   . maxThreads 1 $ (S.fromList [1,2]) <> (S.fromList [3,4])) >>= print   [1,3,2,4] For this example, we are using  maxThreads 1 so that concurrent thread scheduling does not affect the results and make them unpredictable. Let's now take a more general example: main = (S.toList .   . maxThreads 1 $ (S.fromList [1,2,3]) <> (S.fromList [4,5,6]) <> (S.fromList [7,8,9])) >>= print  [1,4,2,7,5,3,8,6,9] 7This is how the execution of the above stream proceeds: (The scheduler queue is initialized with [S.fromList [1,2,3], (S.fromList [4,5,6]) <> (S.fromList [7,8,9])] assuming the head of the queue is represented by the rightmost item.S.fromList [1,2,3]# is executed, yielding the element 1 and putting [2,3] at the back of the scheduler queue. The scheduler queue now looks like [(S.fromList [4,5,6]) <> (S.fromList [7,8,9]), S.fromList [2,3]].Now ,(S.fromList [4,5,6]) <> (S.fromList [7,8,9]) is picked up for execution, S.fromList [7,8,9]( is added at the back of the queue and S.fromList [4,5,6]# is executed, yielding the element 4 and adding S.fromList [5,6]5 at the back of the queue. The queue now looks like 8[S.fromList [2,3], S.fromList [7,8,9], S.fromList [5,6]].Note that the scheduler queue expands by one more stream component in every pass because one more <> is broken down into two components. At this point there are no more <> operations to be broken down further and the queue has reached its maximum size. Now these streams are scheduled in round-robin fashion yielding [2,7,5,3,8,8,9].As we see above, in a right associated expression composed with <> , only one <> operation is broken down into two components in one execution, therefore, if we have n streams composed using <> it will take n scheduler passes to expand the whole expression. By the time n-th component is added to the scheduler queue, the first component would have received n scheduler passes.Since all streams get interleaved, this operation is not suitable for folding an infinite lazy container of infinite size streams. However, if the streams are small, the streams on the left may get finished before more streams are added to the scheduler queue from the right side of the expression, so it may be possible to fold an infinite lazy container of streams. For example, if the streams are of size n then at most n4 streams would be in the scheduler queue at a time. Note that WSerialT and  ? differ in their scheduling behavior, therefore the output of   even with a single thread of execution is not the same as that of WSerialT See notes in WSerialT, for details about its scheduling behavior.Any exceptions generated by a constituent stream are propagated to the output stream. The output and exceptions from a single stream are guaranteed to arrive in the same order in the resulting stream as they were generated in the input stream. However, the relative ordering of elements from different streams in the resulting stream can vary depending on scheduling and generation delays.Similarly, the   instance of   runs all iterations fairly concurrently using a round robin scheduling. main = drain .   $ do n <- return 3 <> return 2 <> return 1 S.yieldM $ do threadDelay (n * 1000000) myThreadId >>= \tid -> putStrLn (show tid ++ ": Delay " ++ show n) ?ThreadId 40: Delay 1 ThreadId 39: Delay 2 ThreadId 38: Delay 3 streamlyA demand driven left biased parallely composing IO stream of elements of type a. See   documentation for more details. streamlyThe  operation (<>) for   merges two streams concurrently with priority given to the first stream. In s1 <> s2 <> s3 ... the streams s1, s2 and s3 are scheduled for execution in that order. Multiple scheduled streams may be executed concurrently and the elements generated by them are served to the consumer as and when they become available. This behavior is similar to the scheduling and execution behavior of actions in a single async stream.Since only a finite number of streams are executed concurrently, this operation can be used to fold an infinite lazy container of streams. import Streamly import qualified Streamly.Prelude4 as S import Control.Concurrent main = (S.toList .  7 $ (S.fromList [1,2]) <> (S.fromList [3,4])) >>= print   [1,2,3,4] Any exceptions generated by a constituent stream are propagated to the output stream. The output and exceptions from a single stream are guaranteed to arrive in the same order in the resulting stream as they were generated in the input stream. However, the relative ordering of elements from different streams in the resulting stream can vary depending on scheduling and generation delays.!Similarly, the monad instance of   may run each iteration concurrently based on demand. More concurrent iterations are started only if the previous iterations are not able to produce enough output for the consumer. main = drain .   $ do n <- return 3 <> return 2 <> return 1 S.yieldM $ do threadDelay (n * 1000000) myThreadId >>= \tid -> putStrLn (show tid ++ ": Delay " ++ show n) ?ThreadId 40: Delay 1 ThreadId 39: Delay 2 ThreadId 38: Delay 3 streamlyGenerate a stream asynchronously to keep it buffered, lazily consume from the buffer.Internal streamlyMake the stream producer and consumer run concurrently by introducing a buffer between them. The producer thread evaluates the input stream until the buffer fills, it terminates if the buffer is full and a worker thread is kicked off again to evaluate the remaining stream when there is space in the buffer. The consumer consumes the stream lazily from the buffer.Internal streamlyPolymorphic version of the  operation  of  . Merges two streams possibly concurrently, preferring the elements from the left one when available. streamlySame as  . streamly(Fix the type of a polymorphic stream as  . streamlyPolymorphic version of the  operation  of  . Merges two streams concurrently choosing elements from both fairly. streamly(Fix the type of a polymorphic stream as  . /(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone -0>? streamly'A serial IO stream of elements of type a" with concurrent lookahead. See   documentation for more details. streamlyThe  operation for   appends two streams. The combined stream behaves like a single stream with the actions from the second stream appended to the first stream. The combined stream is evaluated in the speculative style. This operation can be used to fold an infinite lazy container of streams. import Streamly import qualified Streamly.Prelude4 as S import Control.Concurrent main = do xs <- S.toList .   $ (p 1 |: p 2 |: nil) <> (p 3 |: p 4 |: nil) print xs where p n = threadDelay 1000000 >> return n   [1,2,3,4] Any exceptions generated by a constituent stream are propagated to the output stream.The monad instance of   may run each monadic continuation (bind) concurrently in a speculative manner, performing side effects in a partially ordered manner but producing the outputs in an ordered manner like SerialT. main = S.drain .   $ do n <- return 3 <> return 2 <> return 1 S.yieldM $ do threadDelay (n * 1000000) myThreadId >>= \tid -> putStrLn (show tid ++ ": Delay " ++ show n) ?ThreadId 40: Delay 1 ThreadId 39: Delay 2 ThreadId 38: Delay 3 streamlyPolymorphic version of the  operation  of  . Merges two streams sequentially but with concurrent lookahead. streamly(Fix the type of a polymorphic stream as  .  0!(c) 2019 Composewell Technologies BSD-3-Clausestreamly@composewell.com experimentalGHCNone streamlywriteN n folds a maximum of n' elements from the input stream to an -.Since we are folding to a - n9 should be <= 128, for larger number of elements use an Array from either Streamly.Data.Array or Streamly.Memory.Array. streamly Create a - from the first n3 elements of a list. The array may hold less than n( elements if the length of the list <= n.$It is recommended to use a value of n* <= 128. For larger sized arrays, use an Array from Streamly.Data.Array or Streamly.Memory.Array streamly Create a - from the first n7 elements of a stream. The array is allocated to size n", if the stream terminates before n- elements then the array may hold less than n elements.&For optimal performance use this with n <= 128.-. -. E!(c) 2019 Composewell Technologies BSD-3-Clausestreamly@composewell.com experimentalGHCNone - !(c) 2019 Composewell Technologies BSD-3-Clausestreamly@composewell.com experimentalGHCNone!       F!(c) 2019 Composewell Technologies BSD-3-Clausestreamly@composewell.com experimentalGHCNone !(c) 2019 Composewell Technologies BSD-3-Clausestreamly@composewell.com experimentalGHCNone  G!(c) 2019 Composewell Technologies BSD-3-Clausestreamly@composewell.com experimentalGHCNoneJ  H(c) 2017 Harendra KumarBSD3streamly@composewell.com experimentalGHCNone?       I!(c) 2019 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNoneu streamlyA  is returned by  and is subsequently used to perform read and write operations on a file.streamlyFile handle for standard inputstreamlyFile handle for standard outputstreamlyFile handle for standard errorstreamly?Open a file that is not a directory and return a file handle.  enforces a multiple-reader single-writer locking on files. That is, there may either be many handles on the same file which manage input, or just one handle on the file which manages output. If any open handle is managing a file for output, no new handle can be allocated for that file. If any open handle is managing a file for input, new handles can only be allocated if they do not manage output. Whether two files are the same is implementation-dependent, but they should normally be the same if they have the same absolute path name and neither has been renamed, for example.streamly readArrays h+ reads a stream of arrays from file handle h4. The maximum size of a single array is limited to defaultChunkSize.  ignores the prevailing  TextEncoding and  NewlineMode on the . .readArrays = readArraysOfUpto defaultChunkSizestreamlyreadInChunksOf chunkSize handle reads a byte stream from a file handle, reads are performed in chunks of up to  chunkSize2. The stream ends as soon as EOF is encountered.streamlyS.toList $ words FL.toList (S.fromList "fold these words")["fold", "these", "words"] words = S.wordsBy isSpaceInternal streamly8Unfold a stream to character streams using the supplied 7 and concat the results suffixing a newline character \n to each stream.Internal streamlyUnfold the elements of a stream to character streams using the supplied  and concat the results with a whitespace character infixed between the streams.Internal  6!(c) 2018 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone?H streamlyBreak a string up into a stream of strings at newline characters. The resulting strings do not contain newlines. lines = S.lines A.write9S.toList $ lines $ S.fromList "lines\nthis\nstring\n\n\n"["lines","this","string","",""] streamlyBreak a string up into a stream of strings, which were delimited by characters representing white space. words = S.words A.writeS.toList $ words $ S.fromList "A newline\nis considered white space?"7["A", "newline", "is", "considered", "white", "space?"] streamlyFlattens the stream of  Array Char8, after appending a terminating newline to each string.  is an inverse operation to  .;S.toList $ unlines $ S.fromList ["lines", "this", "string"]"lines\nthis\nstring\n" unlines = S.unlines A.readNote that, in general unlines . lines /= id streamlyFlattens the stream of  Array Char5, after appending a separating space to each string.  is an inverse operation to  .=S.toList $ unwords $ S.fromList ["unwords", "this", "string"]"unwords this string" unwords = S.unwords A.readNote that, in general unwords . words /= id  O!(c) 2018 Composewell TechnologiesBSD3streamly@composewell.com experimentalGHCNone?IO  P(c) 2017 Harendra KumarBSD3streamly@composewell.comNoneIQRSQRTQRUQRVQWXYZ[YZ\YZ]YZ^YZ_YZ`YZaYZbYZcYZdYZeYfgYfhYfhijklmnooppqrstuvwxyz{| } } ~ ~                                                                               ;<    h h                                          K                 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"""""""""C""""""""""""""""""""""""""""""""""""""""""##########################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&C&''''''''''((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))*****************************************++++++++++++++++++++++++++++++++C++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + + ++ +++++++++ + ++++++++++++++++++++++++ ++ +++++++++ + + ++++++++ ++ + ++++ +++ ++ + + + ++ + + + ++ + ++ ++ + + + + ++++++++ + + + +++++++++++++++ ++ ,, ,, ,,, , , , -- - - -- - - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . / / / / / / / / / / / / / / / / 000000000000C000 C  C        1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 12 2 2 2 2 2 2 2 2 2 2 2 2 22 2 2 2 2 2 22 3 3 3 3 3 3 3 3 33 3 3 3 3 3 3 3 3 3 3 3 3 33 4 4 4 4 4 44 4 4 4 4 4 44 4 45 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 55 5 5 6 6 66 7 7 7 7 7 7 88 8 8      Q  Y  Q  Q  QR Q   QR QBQB Q  Q  Q  Q  QR QR QB QR QR   Q  Q  Q QR QR QR QR QR QR Q QR ? ? @ @ @ @ @ @ Q  @ @ @ @ @ Q  QBQR Q  Q Q  Q  Q Q Q Q Q Q Q Q  QR Q Q Q Q   I I I I I I I II I I IQ  I Q   Q  Q %streamly-0.7.3-6HCcd0BjNtHE1KeC1e1yQeStreamlyStreamly.Internal.BaseCompat!Streamly.Internal.Data.Prim.Array"Streamly.Internal.Mutable.Prim.VarStreamly.Internal.Data.ArrayStreamly.Internal.Control.MonadStreamly.Internal.Data.Atomics'Streamly.Internal.Data.Prim.Array.Types!Streamly.Internal.Data.Sink.Types'Streamly.Internal.Data.SmallArray.Types+Streamly.Internal.Data.Stream.StreamDK.Type&Streamly.Internal.Data.Stream.StreamDKStreamly.Internal.Data.Strict!Streamly.Internal.Data.Pipe.TypesStreamly.Internal.Data.PipeStreamly.Internal.Data.Time!Streamly.Internal.Data.Time.Units!Streamly.Internal.Data.Time.ClockStreamly.Internal.Data.SVar*Streamly.Internal.Data.Stream.StreamK.Type%Streamly.Internal.Data.Stream.StreamK"Streamly.Internal.Data.Stream.SVar!Streamly.Internal.Data.Fold.Types*Streamly.Internal.Data.Stream.StreamD.TypeStreamly.Internal.Data.SinkStreamly.Internal.Data.Fold#Streamly.Internal.Data.Parser.Types!Streamly.Internal.Data.Parser.TeeStreamly.Internal.Data.Parser#Streamly.Internal.Data.Unfold.Types#Streamly.Internal.Data.Unicode.Char$Streamly.Internal.Memory.Array.Types%Streamly.Internal.Data.Stream.StreamDStreamly.Internal.Data.Unfold%Streamly.Internal.Data.Stream.Prelude!Streamly.Internal.Data.Stream.Zip$Streamly.Internal.Data.Stream.SerialStreamly.Internal.Memory.Array)Streamly.Internal.Data.Stream.CombinatorsStreamly.Internal.Data.List&Streamly.Internal.Data.Stream.Parallel)Streamly.Internal.Data.Stream.EnumerationStreamly.Internal.Prelude$Streamly.Internal.Memory.ArrayStream Streamly.Internal.FileSystem.Dir#Streamly.Internal.Data.Stream.Async#Streamly.Internal.Data.Stream.Ahead!Streamly.Internal.Data.SmallArray Streamly.Internal.Network.Socket"Streamly.Internal.Network.Inet.TCP#Streamly.Internal.FileSystem.Handle!Streamly.Internal.FileSystem.File%Streamly.Internal.Data.Unicode.Stream&Streamly.Internal.Memory.Unicode.ArrayStreamly.FileSystem.IOVecStreamly.FileSystem.FDIOControl.Monad.Trans.ListListTmanysomeControl.ApplicativeStreamly.Data.FoldStreamly.Memory.MallocStreamly.Memory.RingStreamly.Data.Unfold Data.FoldablefoldStreamly.Memory.ArrayStreamly.Data.SmallArrayStreamly.Data.Prim.ArrayStreamly.Data.ArrayStreamly.PreludeStreamly.FileSystem.FDAdefaultChunkSizeStreamly.Network.SocketStreamly.Network.Inet.TCPStreamly.FileSystem.HandleStreamly.Data.Unicode.StreamStreamly.TutorialbaseGHC.Base<> SemigroupstimessconcatGHC.ErrerrorWithoutStackTrace'primitive-0.7.1.0-Jxsyd70oUttYiCXCa0HqVData.Primitive.Types setOffAddr# writeOffAddr# readOffAddr# indexOffAddr# setByteArray#writeByteArray#readByteArray#indexByteArray# alignment#sizeOf#PrimData.Primitive.Arrayarray#Array#.discardatomicModifyIORefCASatomicModifyIORefCAS_ writeBarrierstoreLoadBarrierMutablePrimArray PrimArray newPrimArrayresizeMutablePrimArrayshrinkMutablePrimArraywritePrimArrayunsafeFreezePrimArrayindexPrimArraysizeofPrimArrayfoldrPrimArrayfoldlPrimArray'$fShowPrimArray$fOrdPrimArray $fEqPrimArraySinkSmallMutableArray SmallArray newSmallArrayreadSmallArraywriteSmallArrayindexSmallArrayMindexSmallArrayindexSmallArray##cloneSmallArraycloneSmallMutableArrayfreezeSmallArrayunsafeFreezeSmallArraythawSmallArrayunsafeThawSmallArraycopySmallArraycopySmallMutableArraysizeofSmallArraysizeofSmallMutableArraytraverseSmallArrayPmapSmallArray' runSmallArraysmallArrayFromListNsmallArrayFromList$fDataSmallArray$fRead1SmallArray$fReadSmallArray$fShow1SmallArray$fShowSmallArray$fIsListSmallArray$fMonoidSmallArray$fSemigroupSmallArray$fMonadFixSmallArray$fMonadZipSmallArray$fMonadPlusSmallArray$fMonadFailSmallArray$fAlternativeSmallArray$fApplicativeSmallArray$fFunctorSmallArray$fTraversableSmallArray$fFoldableSmallArray$fOrdSmallArray$fOrd1SmallArray$fEqSmallArray$fEq1SmallArray$fDataSmallMutableArray$fEqSmallMutableArray$fMonadSmallArrayStreamStepYieldStopnilconsconsMunfoldrMunfoldr replicateMunconsfoldrSdrainEither'Left'Right'Maybe'Just'Nothing'Tuple4'Tuple3'Tuple'toMaybe $fShowEither' $fShowMaybe' $fShowTuple4' $fShowTuple3' $fShowTuple'Pipe PipeStateConsumeProduceContinuezipWithteemapcompose $fArrowPipe$fCategoryTYPEPipe$fSemigroupPipe$fApplicativePipe $fFunctorPipemapMperiodic withClockRelTime RelTime64AbsTime TimeUnit64TimeUnitTimeSpecsecnsec MilliSecond64 MicroSecond64 NanoSecond64 toAbsTime fromAbsTime toRelTime64 fromRelTime64 diffAbsTime64addToAbsTime64 toRelTime fromRelTime diffAbsTime addToAbsTimeshowNanoSecond64 showRelTime64 $fNumTimeSpec $fOrdTimeSpec$fTimeUnitMilliSecond64$fTimeUnitMicroSecond64$fTimeUnitNanoSecond64$fTimeUnitTimeSpec$fTimeUnit64MilliSecond64$fTimeUnit64MicroSecond64$fTimeUnit64NanoSecond64 $fEqRelTime $fReadRelTime $fShowRelTime $fNumRelTime $fOrdRelTime $fEqRelTime64$fReadRelTime64$fShowRelTime64$fEnumRelTime64$fBoundedRelTime64$fNumRelTime64$fRealRelTime64$fIntegralRelTime64$fOrdRelTime64 $fEqAbsTime $fOrdAbsTime $fShowAbsTime $fEqTimeSpec$fReadTimeSpec$fShowTimeSpec$fEqMilliSecond64$fReadMilliSecond64$fShowMilliSecond64$fEnumMilliSecond64$fBoundedMilliSecond64$fNumMilliSecond64$fRealMilliSecond64$fIntegralMilliSecond64$fOrdMilliSecond64$fEqMicroSecond64$fReadMicroSecond64$fShowMicroSecond64$fEnumMicroSecond64$fBoundedMicroSecond64$fNumMicroSecond64$fRealMicroSecond64$fIntegralMicroSecond64$fOrdMicroSecond64$fEqNanoSecond64$fReadNanoSecond64$fShowNanoSecond64$fEnumNanoSecond64$fBoundedNanoSecond64$fNumNanoSecond64$fRealNanoSecond64$fIntegralNanoSecond64$fOrdNanoSecond64Clock MonotonicRealtimeProcessCPUTime ThreadCPUTime MonotonicRawMonotonicCoarseUptimeRealtimeCoarsegetTime$fStorableTimeSpec $fEqClock $fEnumClock$fGenericClock $fReadClock $fShowClockHeapDequeueResultClearingWaitingReadyRunInIOrunInIO MonadAsyncState streamVarSVar svarStylesvarMrun svarStopStyle svarStopBy outputQueueoutputDoorBell readOutputQ postProcessoutputQueueFromConsumeroutputDoorBellFromConsumermaxWorkerLimitmaxBufferLimitpushBufferSpacepushBufferPolicypushBufferMVar remainingWork yieldRateInfoenqueue isWorkDone isQueueDone needDoorBellworkLoop workerThreads workerCount accountThreadworkerStopMVar svarStatssvarRefsvarInspectMode svarCreator outputHeapaheadWorkQueue SVarStopStyleStopNoneStopAnyStopByLimit UnlimitedLimited SVarStatstotalDispatches maxWorkers maxOutQSize maxHeapSize maxWorkQSizeavgWorkerLatencyminWorkerLatencymaxWorkerLatency svarStopTime YieldRateInfosvarLatencyTargetsvarLatencyRangesvarRateBuffersvarGainedLostYieldssvarAllTimeLatencyworkerBootstrapLatencyworkerPollingIntervalworkerPendingLatencyworkerCollectedLatencyworkerMeasuredLatencyRaterateLowrateGoalrateHigh rateBuffer WorkerInfoworkerYieldMaxworkerYieldCountworkerLatencyStart SVarStyleAsyncVar WAsyncVar ParallelVarAheadVarAheadHeapEntryAheadEntryNullAheadEntryPureAheadEntryStream ChildEvent ChildYield ChildStop ThreadAbortdefState adaptState setYieldLimit getYieldLimit setMaxThreads getMaxThreads setMaxBuffer getMaxBuffer setStreamRate getStreamRatesetStreamLatencysetInspectModegetInspectMode cleanupSVarcleanupSVarFromWorkercollectLatencydumpSVar printSVar withDiagMVarcaptureMonadStatedoForkfork forkManageddecrementYieldLimitincrementYieldLimitdecrementBufferLimitincrementBufferLimitsendsendToProducersendStopToProducerworkerUpdateLatencyupdateYieldCountworkerRateControl sendYieldsendStop enqueueLIFO enqueueFIFO enqueueAheadreEnqueueAheadqueueEmptyAhead dequeueAhead withIORefdequeueFromHeapdequeueFromHeapSeq heapIsSanerequeueOnHeapTop updateHeapSeq delThread modifyThreadhandleChildExceptionhandleFoldExceptionrecordMaxWorkers pushWorkerParisBeyondMaxRatedispatchWorkerPacedreadOutputQBasicreadOutputQBoundedreadOutputQPacedpostProcessBoundedpostProcessPacedgetYieldRateInfo newSVarStatssendFirstWorker newAheadVarnewParallelVar toStreamVar$fExceptionThreadAbort $fOrdLimit $fEqLimit $fShowWork$fEqSVarStopStyle$fShowSVarStopStyle $fShowLimit$fShowLatencyRange $fEqSVarStyle$fShowSVarStyle$fShowThreadAbort $fEqCount $fReadCount $fShowCount $fEnumCount$fBoundedCount $fNumCount $fRealCount$fIntegralCount $fOrdCount StreamingIsStreamtoStream fromStream|:MkStreamadaptmkStream fromStopK fromYieldKconsK.:nilMyieldyieldMconsMByfoldStreamShared foldStream consMStreamfoldrSMbuildbuildSbuildSMbuildMsharedMaugmentS augmentSMfoldrMserialconjoin mapMSerialunSharebindWith concatMapBy concatMap $fMonadStream$fApplicativeStream$fMonadTransStream$fFunctorStream$fMonoidStream$fSemigroupStream$fIsStreamStreamoncerepeatMrepeat replicate fromIndicesM fromIndicesiterateiterateM fromFoldablefromList fromStreamKfoldrfoldrTfoldr1foldlx'foldl'foldlMx'foldlM'foldlSfoldlTnullheadtailmfixinitelemnotElemallanylastminimum minimumBymaximum maximumBy!!lookupfindMfind findIndicesmapM_toList toStreamKhoistscanlx'scanl'filtertake takeWhiledrop dropWhilesequence intersperseM intersperseinsertBydeleteByreversemapMaybezipWithMmergeByMmergeBythe withLocal fromStreamVarfromSVartoSVar fromProducer fromConsumer pushToFoldFold2Foldsimplify toListRevFlmaplmapMlfilterlfilterM lcatMaybesltake ltakeWhile duplicate initializerunStep lchunksOf lchunksOf2 lsessionsOf$fFloatingFold$fFractionalFold $fNumFold $fMonoidFold$fSemigroupFold$fApplicativeFold $fFunctorFold GroupState GroupStart GroupBuffer GroupYield GroupFinishUnStreamSkip fromStreamD concatMapMfoldrMxeqBycmpBygroupsOf groupsOf2 $fFunctorStep$fMonadThrowStreamtoFold distributedemuxunzipMunzipdrainMmkPuremkPureIdmkFoldmkFoldId generally transformdrainBydrainBy2lengthsumproductmeanvariancestdDevrollingHashWithSalt rollingHashrollingHashFirstNmconcatfoldMapfoldMapMdrainN drainWhileindex findIndex elemIndexandorsplitAtspanByspanbreak spanByRolling distribute_ partitiondemuxWithDefault_demux_ demuxDefault_classify foldChunkstoParallelSVartoParallelSVarLimited ParseErrorParserError splitWithalt splitMany splitSomediedieM$fMonadPlusParser$fAlternativeParser$fApplicativeParser$fFunctorParser$fExceptionParseError $fMonadParser$fShowParseErrorteeWith teeWithFst teeWithMinshortestlongestfromFoldpeekeofsatisfytakeEQtakeGE takeWhile1 sliceSepBy sliceEndWithsliceBeginWith sliceSepByMaxwordBygroupBy lookAhead deintercalatechoice countBetweencountmanyTillUnfold isAsciiAlphaMonadMutVarnewVarwriteVarreadVar modifyVar' FlattenState OuterLoop InnerLoopaStartaEndaBoundmemcpymemcmpunsafeInlineIObytesToElemCountnewArray withNewArray unsafeSnocsnocrealloc shrinkToFit unsafeIndexIO unsafeIndex byteLength byteCapacity toStreamD toStreamDRev toStreamKRevwriteN writeNAlignedwriteNAlignedUnmanaged writeNUnsafetoArrayMinChunkwrite writeAligned fromStreamDNfromStreamDArraysOf flattenArraysflattenArraysRev fromListN spliceTwo mkChunkSize mkChunkSizeKBunlinesspliceWithDoublingpackArraysChunksOflpackArraysChunksOf groupIOVecsOfbreakOnsplitOn $fMonoidArray$fSemigroupArray $fOrdArray $fNFDataArray $fEqArray $fIsListArray$fIsStringArray $fReadArray $fShowArrayInterleaveStateInterleaveFirstInterleaveSecondInterleaveSecondOnlyInterleaveFirstOnly AppendState AppendFirst AppendSecondConcatUnfoldInterleaveStateConcatUnfoldInterleaveOuterConcatUnfoldInterleaveInnerConcatUnfoldInterleaveInnerLConcatUnfoldInterleaveInnerRConcatMapUStateConcatMapUOuterConcatMapUInnerunfoldenumerateFromStepIntegralenumerateFromToIntegralenumerateFromIntegralenumerateFromThenToIntegralenumerateFromThenIntegralenumerateFromStepNumnumFrom numFromThenenumerateFromToFractionalenumerateFromThenToFractional generateMgenerate fromListM fromPrimVar liftInner runReaderT evalStateT runStateT parselMx' splitParseheadElse toListRevreverse'splitSuffixBy'groupsBygroupsRollingBysplitBy splitSuffixBywordsBy splitSuffixOn splitInnerBysplitInnerBySuffix isPrefixOfisSubsequenceOf stripPrefix concatMapUconcatUnfoldInterleaveconcatUnfoldRoundrobinappend interleave interleaveMininterleaveSuffixinterleaveInfix roundRobingintercalateSuffixinterposeSuffix gintercalate interposegbracketnewFinalizedIORefrunIORefFinalizerclearIORefFinalizerbeforeafterafterIO onExceptionbracket bracketIOfinally finallyIOhandle prescanlM' prescanl' postscanlMx' postscanlx'scanlMx' postscanlM' postscanl' postscanlM postscanlscanlM'scanlMscanlscanl1Mscanl1scanl1M'scanl1' rollingMapM rollingMaptaptapOffsetEvery pollCountstapRate takeWhileM dropWhileMfilterMuniqintersperseSuffixintersperseSuffixBySpan mapMaybeMindexedindexedRrunFoldtoSVarParallel mkParallelD mkParallelnewCallbackStreamtapAsynclastN takeByTime dropByTime currentTimesupply supplyFirst supplySecond discardFirst discardSecondswap mapMWithInput fromStream1 fromStream2effect singletonM singletonidentityconst teeZipWithconcat outerProduct gbracketIO fromStreamS toStreamSfoldWith foldMapWith forEachWithZipAsync ZipAsyncM ZipSerial ZipStream ZipSerialM zipAsyncWithM zipAsyncWith zipSeriallyzipping zipAsyncly zippingAsync$fTraversableZipSerialM$fFoldableZipSerialM$fApplicativeZipSerialM$fFunctorZipSerialM$fNFData1ZipSerialM$fNFDataZipSerialM$fIsStringZipSerialM$fReadZipSerialM$fShowZipSerialM$fOrdZipSerialM$fEqZipSerialM$fIsListZipSerialM$fIsStreamZipSerialM$fApplicativeZipAsyncM$fFunctorZipAsyncM$fIsStreamZipAsyncM$fSemigroupZipAsyncM$fMonoidZipAsyncM$fSemigroupZipSerialM$fMonoidZipSerialM InterleavedTWSerialWSerialTStreamTSerialSerialTserially wSerially interleavingwSerial wSerialFst wSerialMin<=>$fTraversableSerialT$fFoldableSerialT$fNFData1SerialT$fNFDataSerialT$fIsStringSerialT $fReadSerialT $fShowSerialT $fOrdSerialT $fEqSerialT$fIsListSerialT$fMonadStatesSerialT$fMonadReaderrSerialT$fMonadThrowSerialT$fMonadIOSerialT$fMonadBasebSerialT$fFunctorSerialT$fApplicativeSerialT$fMonadSerialT$fIsStreamSerialT$fTraversableWSerialT$fFoldableWSerialT$fNFData1WSerialT$fNFDataWSerialT$fIsStringWSerialT$fReadWSerialT$fShowWSerialT $fOrdWSerialT $fEqWSerialT$fIsListWSerialT$fMonadStatesWSerialT$fMonadReaderrWSerialT$fMonadThrowWSerialT$fMonadIOWSerialT$fMonadBasebWSerialT$fFunctorWSerialT$fMonadWSerialT$fApplicativeWSerialT$fMonoidWSerialT$fSemigroupWSerialT$fIsStreamWSerialT$fMonadTransWSerialT$fSemigroupSerialT$fMonoidSerialT$fMonadTransSerialT fromStreamN toStreamRevread unsafeRead readIndex writeIndexstreamTransform streamFold maxThreads maxBufferrateavgRateminRatemaxRate constRate maxYields printState inspectModeZipList toZipSerialListtoSerialConsNil fromZipList toZipList $fIsListList$fIsStringList$fIsListZipList$fIsStringZipList $fShowZipList $fReadZipList $fEqZipList $fOrdZipList$fNFDataZipList$fNFData1ZipList$fSemigroupZipList$fMonoidZipList$fFunctorZipList$fFoldableZipList$fApplicativeZipList$fTraversableZipList $fShowList $fReadList$fEqList $fOrdList $fNFDataList $fNFData1List$fSemigroupList $fMonoidList $fFunctorList$fFoldableList$fApplicativeList$fTraversableList $fMonadListParallel ParallelTparallel parallelFst parallelMindistributeAsync_ parallely$fMonadStatesParallelT$fMonadReaderrParallelT$fMonadThrowParallelT$fMonadIOParallelT$fMonadBasebParallelT$fFunctorParallelT$fMonadParallelT$fApplicativeParallelT$fMonoidParallelT$fSemigroupParallelT$fIsStreamParallelT$fMonadTransParallelT Enumerable enumerateFromenumerateFromToenumerateFromThenenumerateFromThenToenumerateFromFractionalenumerateFromThenFractionalenumerateFromToSmallenumerateFromThenToSmallenumerateFromThenSmallBounded enumerate enumerateToenumerateFromBounded$fEnumerableIdentity$fEnumerableRatio$fEnumerableFixed$fEnumerableDouble$fEnumerableFloat$fEnumerableNatural$fEnumerableInteger$fEnumerableWord64$fEnumerableWord32$fEnumerableWord16$fEnumerableWord8$fEnumerableWord$fEnumerableInt64$fEnumerableInt32$fEnumerableInt16$fEnumerableInt8$fEnumerableInt$fEnumerableChar$fEnumerableOrdering$fEnumerableBool$fEnumerable() fromFoldableMeach fromHandle fromCallbackfoldxfoldl1'foldxMparse runStreamrunNrunWhile elemIndices isSuffixOf isInfixOf stripSuffix dropPrefix dropInfix dropSuffixtoHandletoPure toPureRev|$ applyAsync|&|$. foldAsync|&.scanxscanpostscan delayPostinterjectSuffix mergeAsyncBy mergeAsyncByM concatMapWith roundrobinconcatM concatUnfold intercalateintercalateSuffixconcatMapIterateWithconcatMapTreeWithconcatMapLoopWithconcatMapTreeYieldLeavesWithchunksOf chunksOf2arraysOf intervalsOfgroupsByRollinggroups splitOnSuffixsplitWithSuffix splitOnSeqsplitOnSuffixSeq splitBySeqsplitWithSuffixSeqtraceclassifySessionsByclassifyKeepAliveSessionsclassifySessionsOf usingStateT usingReaderT concatRevcompacttoArray readEither readFilesreadDirstoEithertoFilestoDirsWAsyncWAsyncTAsyncAsyncTmkAsyncKmkAsyncasync<|asynclywAsyncwAsyncly$fMonadStatesAsyncT$fMonadReaderrAsyncT$fMonadThrowAsyncT$fMonadIOAsyncT$fMonadBasebAsyncT$fFunctorAsyncT $fMonadAsyncT$fApplicativeAsyncT$fMonoidAsyncT$fSemigroupAsyncT$fIsStreamAsyncT$fMonadStatesWAsyncT$fMonadReaderrWAsyncT$fMonadThrowWAsyncT$fMonadIOWAsyncT$fMonadBasebWAsyncT$fFunctorWAsyncT$fMonadWAsyncT$fApplicativeWAsyncT$fMonoidWAsyncT$fSemigroupWAsyncT$fIsStreamWAsyncT$fMonadTransWAsyncT$fMonadTransAsyncTAheadAheadTaheadaheadly$fMonadStatesAheadT$fMonadReaderrAheadT$fMonadThrowAheadT$fMonadIOAheadT$fMonadBasebAheadT$fFunctorAheadT $fMonadAheadT$fApplicativeAheadT$fMonoidAheadT$fSemigroupAheadT$fIsStreamAheadT$fMonadTransAheadT$fNFDataSmallArray readSlice$fNFDataPrimArray runStreaming runStreamTrunInterleavedT runParallelT runAsyncT runZipStream runZipAsyncSockSpec sockFamilysockType sockProtosockOpts handleWithM handleWithaccept connections writeChunktoChunksWithBufferOftoChunksreadChunksWithBufferOf readChunkstoBytesreadWithBufferOf fromChunks writeChunkswriteChunksWithBufferOf writeStringsfromBytesWithBufferOfwriteWithBufferOf fromBytesacceptOnAddrWith acceptOnAddracceptOnPortWith acceptOnPortacceptOnPortLocalconnectionsOnAddrWithconnectionsOnAddrconnectionsOnPortconnectionsOnLocalHostconnectwithConnectionMusingConnectionwithConnectiontransformBytesWith getChunksgetBytestoBytesWithBufferOf writeArray putChunks putStringsputLinesputBytesfromChunksWithBufferOfwrite2withFile appendArray appendChunksappendWithBufferOf DecodeError DecodeState CodePoint decodeUtf8DdecodeUtf8LenientDresumeDecodeUtf8EitherDdecodeUtf8EitherDdecodeUtf8ArraysDdecodeUtf8ArraysLenientD encodeUtf8D decodeLatin1 encodeLatin1encodeLatin1Lax decodeUtf8decodeUtf8Arrays decodeUtf8LaxdecodeUtf8EitherresumeDecodeUtf8EitherdecodeUtf8ArraysLenient encodeUtf8 stripStartlineswordsunwords$fShowDecodeError$fShowCodingFailureModeIOVeciovBaseiovLenc_writev c_safe_writevwriteAllwritev writevAllghc-prim GHC.TypesIODoubleCharIntWordData.Functor.IdentityIdentityControl.Monad.Primitive PrimMonad? Data.EitherEither GHC.MaybeMaybeMonadGHC.IntInt64integer-wired-inGHC.Integer.TypeIntegerpuretransformers-0.5.6.2Control.Monad.Trans.ClassliftFoldableJust GHC.FloatFloatingGHC.Real FractionalGHC.NumNumMonoid<*> sequence_mappendmemptyTrueFalseLeftRightGHC.Listzipmzeroemptymplus<|> Alternative Applicative Data.Functor<$>.mallocForeignPtrAlignedBytes%mallocForeignPtrAlignedUnmanagedBytesRingnew unsafeInsertunsafeEqArrayN unsafeEqArrayunsafeFoldRingGHC.PtrPtrunsafeFoldRingMunsafeFoldRingFullM ringStart ringBoundNothingfmapGHC.EnumEnummaxBoundBoundedIntegralenumFrom enumFromThen enumFromToenumFromThenTotoEnumminBoundoddForeign.StorableStorable$ Data.MaybefromJustisJust-modControl.Monad.Trans.ReaderReaderT Control.Monad.Trans.State.StrictStateTHandleopenFilestdinstdoutstderr readArraysreadInChunksOf writeArrayswriteArraysPackedUptowriteInChunksOf GHC.IO.IOModeIOModereadArraysOfUptoGHC.WordWord8&network-3.1.2.1-I09Sy6M5CNJIMsILXCwpAoNetwork.Socket.TypesSocketGHC.IO.Handle.TypesGHC.IO.Handle.FD