h&(      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGH I J K L MNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                                                     !!""###""! !!    !!!!  "" !!$$$$$%%%%%%%%%%%%%%%%&&&&&&&&&&&&&''''''''''''''''''(((((((((((((((((((((((())))))))))))))))))))))***********+++++++++,,,,,,,,,,,,,,,,,,--. Safe-Inferred 14 linear-baseThe IsFun type class is meant to help the type checker fill in blanks. Chances are that you can safely ignore IsFun completely if it's in the type of a function you care. But read on if you are curious.The type class IsFun is a kind of inverse to , it is meant to be read as  a b f if and only if there exists n such that f =  n a b (n can be retrieved as  b f or / f).The reason why  (read its documentation first) is not sufficient for our purpose, is that it can find n if f= is a linear function of the appropriate shape. But what if f4 is partially undetermined? Then it is likely that 3 will be stuck. But we know, for instance, that if f = a1 %1 -> a2 %1 -> c then we must have a1 ~ a2,. The trick is that instance resolution of IsFun will add unification constraints that the type checker has to solve. Look in particular at the instance  a b (a' %p -> f))=: it matches liberally, so triggers on quite underdetermined f, but has equality constraints in its context which will help the type checker. linear-baseThe  type family exists to help the type checker fill in blanks. Chances are that you can safely ignore  completely if it's in the type of a function you care. But read on if you are curious.$The idea is that in a function like 0 some of the type arguments are redundant. The function has an ambiguous type, so you will always have to help the compiler either with a type annotation or a type application. But there are several complete ways to do so. In 0, if you give the values of n, a, and b$, then you can deduce the value of f (indeed, it's  n a b ). With & we can go in the other direction: if b and f$ are both known, then we know that n is  b f returns a  rather than a  because the result is never consumed. It exists to infer arguments to functions such as 0, from the other arguments if they are known. could  theorically% be an associated type family to the  type class. But it's better to make it a closed type family (which can't be associated to a type class) because it lets us give a well-defined error case. In addition, GHC cannot see that 0 /= 1 + (? :: Nat) and as a result we get some overlap which is only allowed in (ordered) closed type families. linear-base n a b represents a function taking n linear arguments of type a and returning a result of type b. linear-base*Converts a structural type-level natural () to a GHC type-level . linear-baseConverts a GHC type-level % to a structural type-level natural ().  Safe-Inferred& Safe-Inferred4  linear-baseTrue iff both are True. NOTE: this is strict and not lazy! linear-baseTrue iff either is True NOTE: this is strict and not lazy! linear-basenot b is True iff b is False NOTE: this is strict and not lazy!#&#&32  Safe-Inferred4"y linear-baseThe ! data constructor was renamed to MkSolo in GHC 9.6 (see  /https://github.com/tweag/linear-base/issues/437#437). Because at present there is no linear pattern synonym, and in order to stay compatible with GHC 9.4 we use a constructor and a destructor functions as a workaround (it's quite easy in the case of  anyway). linear-baseSee .  Safe-Inferred01& linear-baseFixupMetaData1 f g copies the metadata from the  GHC.Generics. representation of f  to the representation g0. It also checks that the overall structure of Rep (f ) is the same as g., but does not check that their fields match.Example  instance  1 where type Rep1 Ur = FixupMetaData1 Ur (D1 Any (C1 Any (S1 Any (MP1 'Many Par1))))  linear-baseFixupMetaData a g copies the metadata from the  GHC.Generics. representation of a to the representation g'. It also checks that the structure of Rep a is the same as g, except that g may have MP1 applications under some S1 constructors.Example  instance  (1 a) where type Rep (Ur a) = FixupMetaData (Ur a) (D1 Any (C1 Any (S1 Any (MP1 'Many (Rec0 a))))) 2 Trustworthy )*145;) linear-baseUr a( represents unrestricted values of type a in a linear context. The key idea is that because the contructor holds a- with a regular arrow, a function that uses Ur a linearly can use a however it likes. 7someLinear :: Ur a %1-> (a,a) someLinear (Ur a) = (a,a) linear-baseGet an a out of an Ur a1. If you call this function on a linearly bound Ur a , then the a3 you get out has to be used linearly, for example: restricted :: Ur a %1-> b restricted x = f (unur x) where -- f __must__ be linear f :: a %1-> b f x = ... linear-baseLifts a function on a linear Ur a. linear-base'Lifts a function to work on two linear Ur a. Safe-Inferred+ linear-base;A type whose instances are defined generically, using the  representation.  is a higher-kinded version of . to head normal form, therefore is not guaranteed to consume x8 when the resulting computation is consumed. Therefore, seq* cannot be linear in it's first argument. linear-baseBeware: (.) is not compatible with the standard one because it is higher-order and we don't have sufficient multiplicity polymorphism yet. linear-baseConvenience operator when a higher-order function expects a non-linear arrow but we have a linear arrow. linear-baseA linear version of  for types of kind 56. 01009 7 Safe-Inferred)*42 linear-baseReplicationStream s g dup2 c is the infinite linear stream  repeat (g s) where dup2# is used to make as many copies of s as necessary, and c is used to consume s when consuming the stream.*Although it isn't enforced at type level, dup2# should abide by the same laws as  8: * (first c (dup2 a) D a D second c (dup2 a) (neutrality) * ,first dup2 (dup2 a) D (second dup2 (dup2 a)) (associativity)&This type is solely used to implement 9:4; Safe-Inferred)*14:  linear-base n a b is used to implement 2 without recursion so that we can guarantee that  will be inlined and unrolled.$ is solely used in the signature of . linear-base is a stream-like data structure used to linearly duplicate values. linear-base2Extracts the next item from the "infinite stream"  a. linear-base2Extracts the next item from the "infinite stream"  a. Same function as !, but returning an unboxed tuple. linear-base n as is a list of size n , containing n replicas from as. linear-baseReturns the next item from  a; and efficiently consumes the replicator at the same time. linear-base Comonadic  function. extend f = map f . duplicate linear-baseTakes a function of type #a %1 -> a %1 -> ... %1 -> a %1 -> b, and returns a b: . The replicator is used to supply all the items of type a required by the function. For instance: elim @1 :: (a %1 -> b) %1 -> Replicator a %1 -> b elim @2 :: (a %1 -> a %1 -> b) %1 -> Replicator a %1 -> b elim @3 :: (a %1 -> a %1 -> a %1 -> b) %1 -> Replicator a %1 -> bIt is not always necessary to give the arity argument. It can be inferred from the function argument. elim (,) :: Replicator a %1 -> (a, a) elim (,,) :: Replicator a %1 -> (a, a, a)About the constraints of this function (they won't get in your way): ( n) a b' provides the actual implementation of -; there is an instance of this class for any  (n, a, b) a b f, f ~  ( n) a b, n ~  b f indicate the shape of f* to the typechecker (see documentation of ).4 Safe-Inferred 01=& linear-baseAn unsatisfiable constraint with a user-provided error message. Under an  Unsatisfiable constraint, users can use  to get a value of any type (and runtime representation) they desire. For example, instance Unsatisfiable ('Text "V1 cannot have an Applicative instance because it cannot implement pure") => Applicative V1 where pure = unsatisfiable ( *) = unsatisfiable  linear-baseA constraint that cannot be satisfied. Users should normally use & instead of using this class directly. linear-baseProduce a value of any type (and runtime representation) under an  or  constraint. Safe-Inferred)*014F  linear-baseThe actual implementation of 2, using the inductive natural number it's handed. linear-baseConvert a GHC > to a real inductive natural number. We use this because GHC  offers a friendly API but it's a terrible pain for implementation. linear-base$Plain old inductive natural numbers. linear-baseToLinearN n f g means that f and g are the same with the possible exception of the multiplicities of the first n arrows. linear-base Given that f and g are the same, with the possible exception of the multiplicities of the first n arrows, unsafeLinearityProofN @n @f @g is a fake proof that f and g= are identical. This is used primarily in the definition of , but it can also be used, for example, to coerce a container of functions: linearMany :: forall a b c. [a -> b -> c] %1-> [a %1-> b %1-> c] linearMany = castWithUnsafe (applyUnsafe (UnsafeRefl []) $ unsafeLinearityProofN 2 (a -> b -> c) (a %1-> b %1-> c)) applyUnsafe :: UnsafeEquality f g -> UnsafeEquality x y -> UnsafeEquality (f x) (g y) applyUnsafe UnsafeRefl UnsafeRefl = UnsafeRefl castWithUnsafe :: UnsafeEquality x y -> x %1-> y castWithUnsafe UnsafeRefl x = x The rather explicit handling of coercions seems to be necessary, unfortunately, presumably due to the way GHC eagerly rejects equality constraints it sees as definitely unsatisfiable. linear-baseLinearly typed  unsafeCoerce linear-base8Converts an unrestricted function into a linear function linear-baseLike  but for two-argument functions linear-baseLike ! but for three-argument functions linear-base toLinearN subsumes the functionality of  toLinear1, , and . In particular,  toLinearN @n3 unsafely changes the multiplicities of the first n arrows from any multiplicity to any other multiplicity. To be explicit about how each multiplicity is being changed, you can use additional type arguments.Examples toLinearN @2 :: (a %m-> b %n-> Int) %1-> a %x-> b %y-> Int toLinearN @3 @(_ %m-> _ -> _ %1-> _) @(_ %1-> _ %1-> _ %x-> _) :: (a %m-> b -> c %1-> d) %1-> (a %1-> b %1-> c %x-> d)  = toLinearN @3 < Trustworthy45?H linear-base9A class for generic representations that can be consumed. linear-base?Consume the unit and return the second argument. This is like ; but since the first argument is restricted to be of type () it is consumed, hence seqUnit! is linear in its first argument. linear-baseConsume the first argument and return the second argument. This is like , but the first argument is restricted to be .0= Safe-Inferred)*0145?P  linear-base The laws of  are dual to those of Monoid:1. 4first consume (dup2 a) D a D second consume (dup2 a) ( neutrality)2. ,first dup2 (dup2 a) D (second dup2 (dup2 a)) ( associativity) where the (D)1 sign represents equality up to type isomorphism.3. !dup2 = Replicator.elim (,) . dupR (coherence between  and )4. #consume = Replicator.elim () . dupR (coherence between  and )5. Replicator.extract . dupR = id ( identity)6. *dupR . dupR = (Replicator.map dupR) . dupR ( interchange)!(Laws 1-2 and 5-6 are equivalent)Implementation of  for >? types should be done with  deriving via >@.Implementation of # for other types can be done with  deriving via . Note that at present this mechanism can have performance problems for recursive parameterized types. Specifically, the methods will not specialize to underlying  instances. See  1https://gitlab.haskell.org/ghc/ghc/-/issues/21131this GHC issue. linear-base Creates a  for the given a.-You usually want to define this method using 's A7 instance. For instance, here is an implementation of  [a]: instance Dupable a => Dupable [a] where dupR [] = pure [] dupR (a : as) = (:) <$> dupR a <*> dupR as linear-base Creates two a s from a  a, in a linear fashion. linear-base Creates 3 a s from a  a, in a linear fashion. linear-base Creates 4 a s from a  a, in a linear fashion. linear-base Creates 5 a s from a  a, in a linear fashion. linear-base Creates 6 a s from a  a, in a linear fashion. linear-base Creates 7 a s from a  a, in a linear fashion. linear-base Creates two a s from a  a. Same function as . B Safe-Inferred/1489:\  linear-base m n a5 is used to avoid recursion in the implementation of  so that  can be inlined.2 is solely used in the signature of that function. linear-baseThe  type family exists to help the type checker compute the arity n ~  b f when b ~  n a. linear-base n a b is used to implement 2 without recursion so that we can guarantee that  will be inlined and unrolled.$ is solely used in the signature of . linear-base n a% represents an immutable sequence of n elements of type a" (like a n-tuple), with a linear A instance. linear-baseReturns an empty . linear-base Splits the head and tail of the , returning an unboxed tuple. linear-base Splits the head and tail of the , returning a boxed tuple. linear-baseTakes a function of type #a %1 -> a %1 -> ... %1 -> a %1 -> b, and returns a b . The  n a) is used to supply all the items of type a required by the function. For instance: elim @1 :: (a %1 -> b) %1 -> V 1 a %1 -> b elim @2 :: (a %1 -> a %1 -> b) %1 -> V 2 a %1 -> b elim @3 :: (a %1 -> a %1 -> a %1 -> b) %1 -> V 3 a %1 -> bIt is not always necessary to give the arity argument. It can be inferred from the function argument.About the constraints of this function (they won't get in your way):n ~  ( n)5 is just there to help GHC, and will always be proved ( n) a b' provides the actual implementation of -; there is an instance of this class for any  (n, a, b) a b f, f ~  ( n) a b, n ~  b f indicate the shape of f* to the typechecker (see documentation of ). linear-base"Prepends the given element to the . linear-baseBuilds a n-ary constructor for  n a (i.e. a function taking n linear arguments of type a and returning a  n a). myV :: V 3 Int myV = make 1 2 3About the constraints of this function (they won't get in your way):n ~  ( n)5 is just there to help GHC, and will always be proved ( n) ( n) a' provides the actual implementation of -; there is an instance of this class for any (n, a) a ( n a) f, f ~  ( n) a ( n a), n ~  f* indicate the shape to the typechecker of f (see documentation of ). linear-baseReturns the type-level ( of the context as a term-level integer. linear-base Creates a & of the specified size by consuming a . linear-base Produces a  n a from a  value a.4 Safe-Inferred4\C Safe-Inferred14?_ linear-base DerivingVia combinator for  (resp. DE) given linear  (resp. Monoid). newtype Endo a = Endo (a %1-> a) deriving (Prelude.Semigroup) via NonLinear (Endo a) linear-baseAn  a# is just a linear function of type a %1-> a-. This has a classic monoid definition with  and . linear-baseA linear semigroup a0 is a type with an associative binary operation <> that linearly consumes two as.Laws (same as FG<): * D x D G, y D G, z D G, x <> (y <> z) = (x <> y) <> z linear-baseA linear application of an . linear-baseUseful to treat  unrestricted semigroups as linear ones.0/.321ONMRQPUTSXWV[ZY6H Safe-Inferred14?aM linear-baseA linear monoid is a linear semigroup with an identity on the binary operation.Laws (same as IE.): * D x D G, x <> mempty = mempty <> x = x linear-baseUseful to treat  unrestricted monoids as linear ones. Safe-Inferreda| 0/.321ONMRQPUTSXWV[ZY [ZYXWV3210/.UTSONMRQPJ Trustworthy145?c linear-baseLinear Data Functors should be thought of as containers holding values of type a< over which you are able to apply a linear function of type  a %1-> b on each value of type a5 in the functor and consume a given functor of type f a. linear-baseReplace all occurances of b with the given a and consume the functor f b. linear-base4Discard a consumable value stored in a data functor.44K Safe-Inferred145?i linear-baseData -s can be seen as containers which can be zipped together. A prime example of data  are vectors of known length (ZipLists would be, if it were not for the fact that zipping them together drops values, which we are not allowed to do in a linear container).In fact, an applicative functor is precisely a functor equipped with (pure and) 4liftA2 :: (a %1-> b %1-> c) -> f a %1-> f b %1-> f c. In the case where f = [], the signature of  would specialise to that of zipWith.Intuitively, the type of  means that s can be seen as containers whose "number" of elements is known at compile-time. This includes vectors of known length but excludes Maybe, since this may contain either zero or one value. Similarly, ((->) r) forms a Data >, since this is a (possibly infinitary) container indexed by r, while lists do not, since they may contain any number of elements.'Remarks for the mathematically inclinedAn  is, as in the restricted case, a lax monoidal endofunctor of the category of linear types. That is, it is equipped witha (linear) function  () %1-> f ()"a (linear) natural transformation (f a, f b) %1-> f (a, b)It is a simple exercise to verify that these are equivalent to the definition of . Hence that the choice of linearity of the various arrow is indeed natural.4L Trustworthy145?l linear-baseUse  a to represent a type which can be used many times even when given linearly. Simple data types such as  or [] are . Though, bear in mind that this typically induces a deep copy of the value. Formally,  a is the class of  6https://ncatlab.org/nlab/show/coalgebra+over+a+comonad coalgebras of the  comonad. That is unur (move x) = x 5move @(Ur a) (move @a x) = fmap (move @a) $ move @a xAdditionally, a & instance must be compatible with its  parent instance. That is: 'case move x of {Ur _ -> ()} = consume x (case move x of {Ur x -> (x, x)} = dup2 xM Safe-Inferred.145?v linear-baseThis class handles pattern-matching failure in do-notation. See Control.Monad.Fail for details. linear-baseControl linear monads. A linear monad is one in which you sequence linear functions in a context, i.e., you sequence functions of the form  a %1-> m b. linear-basex >>= g applies a linear function g> linearly (i.e., using it exactly once) on the value of type a inside the value of type m a linear-baseControl linear applicative functors. These represent effectful computations that could produce continuations that can be applied with . linear-baseInject (and consume) a value into an applicative control functor. linear-baseApply the linear function in a control applicative functor to the value of type a in another functor. This is essentialy composing two effectful computations, one that produces a function  f :: a %1-> b( and one that produces a value of type a into a single effectful computation that produces a value of type b. linear-baseliftA2 g consumes g- linearly as it lifts it over two functors: !liftA2 g :: f a %1-> f b %1-> f c. linear-base.Control linear functors. The functor of type f a holds only one value of type a, and represents a computation producing an a with an effect. All control functors are data functors, but not all data functors are control functors. linear-baseMap a linear function g over a control functor f a . Note that g" is used linearly over the single a in f a. linear-baseApply the control fmap over a data functor. linear-base  () = flip   linear-base,Linearly typed replacement for the standard DN function. linear-base7Discard a consumable value stored in a control functor. linear-baseApply the control pure over a data applicative. linear-baseGiven an effect-producing computation that produces an effect-producing computation that produces an a, simplify it to an effect-producing computation that produces an a. linear-baseUse this operator to define Applicative instances in terms of Monad instances. linear-baseFold from left to right with a linear monad. This is a linear version of OP.114414Q Safe-Inferred4w8R Safe-Inferred.4?w linear-baseThis is a newtype for deriving Data.XXX classes from Control.XXX classes.S Safe-Inferred.4?y| linear-base*A (strict) linear state monad transformer. linear-baseUse with care! This consumes the final state, so might be costly at runtime. linear-baseUse with care! This consumes the final state, so might be costly at runtime. linear-base replace s will replace the current state with the new given state, and return the old state.T Safe-Inferred4{ linear-baseA linear reader monad transformer. This reader monad requires that use of the read-only state is explict.!The monad instance requires that r be . This means that you should use the linear reader monad just like the non-linear monad, except that the type system ensures that you explicity use or discard the read-only state (with the  instance). linear-baseProvide an intial read-only state and run the monadic computation in a reader monad transformer  Safe-Inferred4| 8:U Safe-Inferred4~ linear-baseUrT7 transforms linear control monads to non-linear monads.UrT ( s) a) is a non-linear monad with linear state. linear-baseLinearly unwrap the UrT newtype wrapper. linear-baseLift a computation to the UrT monad, provided that the type a can be used unrestricted. linear-base7Extract the inner computation linearly, the inverse of . evalUrT (liftUrT m) = mV Safe-Inferred)*4@ linear-baseA linear version of  Data.Functor.Day.Curried.Curried in the kan-extensions package. We use this for generic traversals. How does it help? Consider a type like data Foo a = Foo a a a a0The generic representation may look roughly like D1 _ (C1 _ ((S1 _ Rec1 :*: S1 _ Rec1) :*: (S1 _ Rec1 :*: S1 _ Rec1))),Traversing this naively requires a bunch of fmap4 applications. Most of them could be removed using , but one aspect can't be. Let's simplify down to the hard bit: m :*: (n :*: o)Traversing this looks like ((:*:)  $ m)  * ((:*:)  $ n  * o)We want to reassociate the applications so the whole reconstruction of the generic representation happens in one place, allowing inlining to (hopefully) erase them altogether. It will end up looking roughly like (x y z -> x :*: (y :*: z))  $ m  * n  * oIn our context, we always have the two functor arguments the same, so something like  Curried f f.  Curried f f a is a lot like f a, as demonstrated directly by  and, in kan-extensions,  liftCurried. It's a sort of "continuation passing style" version. If we have something like Con  $ m  * n  * o -- parenthesized ((Con  $ m)  * n)  * o we can look at what happens next to each field. So the next thing after performing m is to map Con+ over it. The next thing after performing n is to apply Con  $ m to it within the functor. W Safe-Inferred)*4? linear-base*This type class derives the definition of 7 by induction on the generic representation of a type. linear-base!A right-to-left state transformer linear-base/A linear data traversible is a functor of type t a8 where you can apply a linear effectful action of type  a %1-> f b on each value of type a and compose this to perform an action on the whole functor, resulting in a value of type f (t b).To learn more about  , see here:"Applicative Programming with Effects", by Conor McBride and Ross Paterson, !Journal of Functional Programming! 18:1 (2008) 1-13, online at  7http://www.soi.city.ac.uk/~ross/papers/Applicative.html."The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira, in 0Mathematically-Structured Functional Programming, 2006, online at  http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator."An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek, in 0Mathematically-Structured Functional Programming, 2012, online at  http://arxiv.org/pdf/1202.2919. linear-baseImplementation of X" for types which derive (linear) .### Performance noteAt present, this function does not perform well for recursive types like lists; it will not specialize to either ### Example data T $(deriveGeneric1 ''T) instance Traversable T where traverse = genericTraverseNote that, contrary to many other classes in linear-base, we can't define `Traversable T` using deriving via, because the  https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.htmlrole of t, in the type of X , is nominal. Y Safe-Inferred Safe-Inferred Safe-Inferred4GFEGFEZ Safe-Inferred[ Safe-Inferred 145? linear-baseNewtype that must be used with  DerivingVia to get efficient  and  implementations for  types.  Safe-Inferred\ Safe-Inferred45? linear-baseTesting equality on values.The laws are that (==) and (/=) are compatible and (==) is an equivalence relation. So, for all x, y, z,x == x alwaysx == y implies y == xx == y and y == z implies x == z(x == y) D  not (x /= y)44] Safe-Inferred45?V linear-baseLinear Orderings6Linear orderings provide a strict order. The laws for (<=) for all a,b,c: reflexivity:  a \leq a antisymmetry: 0(a \leq b) \land (b \leq a) \rightarrow (a = b) transitivity: 3(a \leq b) \land (b \leq c) \rightarrow (a \leq c) and these "agree" with <:x <= y =  not (y > x)x >= y =  not (y < x)+Unlike in the non-linear setting, a linear compare doesn't follow from <=! since it requires calls: one to <= and one to ==. However, from a linear compare it is easy to implement the others. Hence, the minimal complete definition only contains compare. linear-base compare x y returns an Ordering which is one of GT (greater than), EQ (equal), or LT2 (less than) which should be understood as "x is  (compare x y) y". linear-basemax x y returns the larger input, or y in case of a tie. linear-basemin x y returns the smaller input, or y in case of a tie. )*+44444 Safe-Inferred+)*)*+ Safe-Inferred)*4 linear-baseLinearly consume an Either by applying the first linear function on a value constructed with Left= and the second linear function on a value constructed with Right. linear-base?Get all the left elements in order, and consume the right ones. linear-base?Get all the right elements in order, and consume the left ones. linear-base%Get the left element of a consumable Either with a default linear-base&Get the right element of a consumable Either with a default linear-base Partition and consume a list of Eithers into two lists with all the lefts in one and the rights in the second, in the order they appeared in the initial list. "(' "(' Safe-Inferred.   Safe-Inferred4 linear-base maybe b f m returns (f a) where a is in m if it exists and b otherwise linear-basefromMaybe default m is the a in m if it exists and the default otherwise linear-base maybeToList m4 creates a singleton or an empty list based on the Maybe a. linear-base catMaybes xs discards the Nothings in xs and extracts the as linear-base $mapMaybe f xs = catMaybes (map f xs)%$%$ Safe-Inferred145?  linear-baseA newtype wrapper to give the underlying monoid for a multiplicative structure.Deprecated because F^ (reexported as R) now has a linear  and  instance. linear-baseA newtype wrapper to give the underlying monoid for an additive structure.Deprecated because F_ (reexported as O) now has a linear  and  instance. linear-baseA numeric type that Integers can be embedded into while satisfying all the typeclass laws Integers obey. That is, if there's some property like commutivity of integers x + y == y + x, then we must have: >fromInteger x + fromInteger y == fromInteger y + fromInteger xFor mathy folk:  fromInteger should be a homomorphism over (+) and (*). linear-baseA ! instance is a numeric type with (+), (-), (*)1 and all the following properties: a group with (+) and a  with (*) along with distributive laws. linear-baseA  &https://en.wikipedia.org/wiki/Semiringsemiring class. This is basically a numeric type with mutliplication, addition and with identities for each. The laws: /zero * x = zero a * (b + c) = (a * b) + (a * c) linear-baseA  type with an identity for (*) linear-base#A numeric type with an associative (*) operation linear-baseAn . with inverses that satisfies the laws of an +https://en.wikipedia.org/wiki/Abelian_group abelian group linear-baseAn  type with an identity on (+). linear-base2A type that can be added linearly. The operation (+)0 is associative and commutative, i.e., for all a, b, c '(a + b) + c = a + (b + c) a + b = b + c766  Safe-Inferred4 linear-base filter p xs7 returns a list with elements satisfying the predicate.See ` if you do not want the  constraint. linear-baseReturn the length of the given list alongside with the list itself. linear-base, applied to a predicate p and a list xs, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that satisfy p1 and second element is the remainder of the list. linear-baseNOTE: This does not short-circuit and always traverses the entire list to consume the rest of the elements. linear-baseNOTE: This does not short-circuit and always traverses the entire list to consume the rest of the elements. linear-base:The intersperse function takes an element and a list and  intersperses/ that element between the elements of the list. linear-baseintercalate xs xss is equivalent to (concat (intersperse xs xss)). It inserts the list xs in between the lists in xss and concatenates the result. linear-baseThe transpose function transposes the rows and columns of its argument. linear-baseMap each element of the structure to a monoid, and combine the results. linear-base A variant of # that is strict in the accumulator. linear-baseNOTE: This does not short-circuit, and always consumes the entire container. linear-baseNOTE: This does not short-circuit, and always consumes the entire container. linear-baseNOTE: This does not short-circuit, and always consumes the entire container. linear-baseNOTE: This does not short-circuit, and always consumes the entire container. linear-baseSame as 6, but returns the leftovers instead of consuming them. linear-baseSame as 6, but returns the leftovers instead of consuming them.?DI JK LONMRQPUTSXWV[ZY\]efg -,!  ~}|{zyxwvutsrqponmlkjih gcd\e]f :98><=;D74?654 Safe-Inferred 24?e linear-baseThis is the linear IO monad. It is a newtype around a function that transitions from one State# RealWorld' to another, producing a value of type a along with it. The State# RealWorld7 is the state of the world/machine outside the program. IO b turns into a function of type Resource a %1-> RIO (Ur b) along with threading the  Resource a. is only safe to use on actions which do not release the resource.Note that the result b can be used non-linearly. linear-baseSpecialised variant of ( for actions that don't return a value.    Safe-InferredACBA@ba`_^ba`_^CBA@ Safe-Inferred4¾  linear-baseThe  function outputs the trace message given as its first argument, before returning the second argument as its result. linear-baseLike  , but uses % on the argument to convert it to a  . linear-baseLike 2 but returns the message instead of a third value. linear-baseLike <, but additionally prints a call stack if one is available. linear-baseThe  function outputs the trace message from the IO monad. This sequences the output with respect to other IO actions. linear-baseLike $ but returning unit in an arbitrary 4 context. Allows for convenient use in do-notation. linear-baseLike  , but uses % on the argument to convert it to a  . linear-baseThe  function behaves like  with the difference that the message is emitted to the eventlog, if eventlog profiling is available and enabled at runtime. linear-baseThe  function emits a message to the eventlog, if eventlog profiling is available and enabled at runtime. linear-baseThe  function emits a marker to the eventlog, if eventlog profiling is available and enabled at runtime. The String is the name of the marker. The name is just used in the profiling tools to help you keep clear which marker is which. linear-baseThe  function emits a marker to the eventlog, if eventlog profiling is available and enabled at runtime.  g Safe-Inferred %&)*/24u linear-baseA left-strict pair; the base functor for streams of individual elements.5h Safe-Inferred %&43  linear-baseWhen chunking streams, it's useful to have a combinator that can add an element to the functor that is itself a stream. Basically `consFirstChunk 42 [[1,2,3],[4,5]] = [[42,1,2,3],[4,5]]`. linear-baseThe standard way of inspecting the first item in a stream of elements, if the stream is still 'running'. The Right; case contains a Haskell pair, where the more general inspect would return a left-strict pair. There is no reason to prefer inspect since, if the Right case is exposed, the first element in the pair will have been evaluated to whnf. next :: Control.Monad m => Stream (Of a) m r %1-> m (Either r (a, Stream (Of a) m r)) inspect :: Control.Monad m => Stream (Of a) m r %1-> m (Either r (Of a (Stream (Of a) m r))) linear-baseInspect the first item in a stream of elements, without a return value. linear-baseSplit a succession of layers after some number, returning a streaming or effectful pair. This function is the same as the splitsAt exported by the  Streaming module, but since this module is imported qualified, it can usurp a Prelude name. It specializes to:  splitAt :: Control.Monad m => Int -> Stream (Of a) m r %1-> Stream (Of a) m (Stream (Of a) m r) linear-baseSplit a stream of elements wherever a given element arises. The action is like that of  . >>> S.stdoutLn $ mapped S.toList $ S.split ' ' $ each' "hello world " hello world  linear-baseBreak a sequence upon meeting an element that falls under a predicate, keeping it and the rest of the stream as the return value. >>> rest <- S.print $ S.break even $ each' [1,1,2,3] 1 1 >>> S.print rest 2 3  linear-baseBreak during periods where the predicate is not satisfied, grouping the periods when it is. >>> S.print $ mapped S.toList $ S.breaks not $ S.each' [False,True,True,False,True,True,False] [True,True] [True,True] >>> S.print $ mapped S.toList $ S.breaks id $ S.each' [False,True,True,False,True,True,False] [False] [False] [False]  linear-baseYield elements, using a fold to maintain state, until the accumulated value satifies the supplied predicate. The fold will then be short-circuited and the element that breaks it will be put after the break. This function is easiest to use with ij  >>> rest  -,each' [1..10] & L.purely S.breakWhen L.sum (410) & S.print 1 2 3 4 >>> S.print rest 5 6 7 8 9 10  linear-base4Breaks on the first element to satisfy the predicate linear-base?Stream elements until one fails the condition, return the rest. linear-baseGroup elements of a stream in accordance with the supplied comparison. >>> S.print $ mapped S.toList $ S.groupBy (>=) $ each' [1,2,3,1,2,3,4,3,2,4,5,6,7,6,5] [1] [2] [3,1,2,3] [4,3,2,4] [5] [6] [7,6,5]  linear-base%Group successive equal items together >>> S.toList $ mapped S.toList $ S.group $ each' "baaaaad" ["b","aaaaa","d"] :> () >>> S.toList $ concats $ maps (S.drained . S.splitAt 1) $ S.group $ each' "baaaaaaad" "bad" :> ()  linear-base0Swap the order of functors in a sum of functors. >>> S.toList $ S.print $ separate $ maps S.switch $ maps (S.distinguish (==a)) $ S.each' "banana" a a a "bnn" :> () >>> S.toList $ S.print $ separate $ maps (S.distinguish (==a)) $ S.each' "banana" b n n "aaa" :> ()  linear-baseGiven a stream on a sum of functors, make it a stream on the left functor, with the streaming on the other functor as the governing monad. This is useful for acting on one or the other functor with a fold, leaving the other material for another treatment. It generalizes kl , but actually streams properly. >>> let odd_even = S.maps (S.distinguish even) $ S.each' [1..10::Int] >>> :t separate odd_even separate odd_even :: Monad m => Stream (Of Int) (Stream (Of Int) m) () Now, for example, it is convenient to fold on the left and right values separately: >>> S.toList $ S.toList $ separate odd_even [2,4,6,8,10] :> ([1,3,5,7,9] :> ()) 3Or we can write them to separate files or whatever."Of course, in the special case of Stream (Of a) m r;, we can achieve the above effects more simply by using mn >>> S.toList . S.filter even $ S.toList . S.filter odd $ S.copy $ each' [1..10::Int] [2,4,6,8,10] :> ([1,3,5,7,9] :> ()) But  and  are functor-general. linear-base &filter p = hoist effects (partition p) linear-base5Separate left and right values in distinct streams. (; is a more powerful, functor-general, equivalent using   in place of "). partitionEithers = separate . maps S.eitherToSum lefts = hoist S.effects . partitionEithers rights = S.effects . partitionEithers rights = S.concat linear-baseThe  function takes a  of s and returns a  of all of the % values. concat has the same behavior, but is more general; it works for any foldable container type. linear-baseThe  function is a version of  which can throw out elements. In particular, the functional argument returns something of type  b . If this is $+, no element is added on to the result  . If it is % b, then b is included in the result . linear-baseMap monadically over a stream, producing a new stream only containing the % values. linear-baseChange the effects of one monad to another with a transformation. This is one of the fundamental transformations on streams. Compare with : maps :: (Control.Monad m, Control.Functor f) => (forall x. f x %1-> g x) -> Stream f m r %1-> Stream g m r hoist :: (Control.Monad m, Control.Functor f) => (forall a. m a %1-> n a) -> Stream f m r %1-> Stream f n r linear-base)Standard map on the elements of a stream. >>> S.stdoutLn $ S.map reverse $ each' (words "alpha beta") ahpla ateb  linear-baseMap layers of one functor to another with a transformation. Compare hoist, which has a similar effect on the monadic parameter. +maps id = id maps f . maps g = maps (f . g) linear-baseReplace each element of a stream with the result of a monadic action >>> S.print $ S.mapM readIORef $ S.chain (ior -> modifyIORef ior (*100)) $ S.mapM newIORef $ each' [1..6] 100 200 300 400 500 600  See also  for a variant of this which ignores the return value of the function and just uses the side effects. linear-baseMap layers of one functor to another with a transformation. Compare hoist, which has a similar effect on the monadic parameter. mapsPost id = id mapsPost f . mapsPost g = mapsPost (f . g) mapsPost f = maps fmapsPost is essentially the same as , but it imposes a Control.Functor constraint on its target functor rather than its source functor. It should be preferred if fmap is cheaper for the target functor than for the source functor. linear-baseMap layers of one functor to another with a transformation involving the base monad.This function is completely functor-general. It is often useful with the more concrete type mapped :: (forall x. Stream (Of a) IO x -> IO (Of b x)) -> Stream (Stream (Of a) IO) IO r -> Stream (Of b) IO r >to process groups which have been demarcated in an effectful, IO.-based stream by grouping functions like mo, mp or mq. Summary functions like mr, mP, ms or mt are often used to define the transformation argument. For example: ,>>> S.toList_ $ S.mapped S.toList $ S.split c (S.each' "abcde") ["ab","de"] mu and mv obey these rules: maps id = id mapped return = id maps f . maps g = maps (f . g) mapped f . mapped g = mapped (f <=< g) maps f . mapped g = mapped (fmap f . g) mapped f . maps g = mapped (f <=< fmap g)where f and g are  Control.Monadsmu is more fundamental than mv, which is best understood as a convenience for effecting this frequent composition: -mapped phi = decompose . maps (Compose . phi) linear-baseMap layers of one functor to another with a transformation involving the base monad.  mapsMPost is essentially the same as mapsM, but it imposes a Control.Functor constraint on its target functor rather than its source functor. It should be preferred if fmap is cheaper for the target functor than for the source functor.mapsPost is more fundamental than  mapsMPost, which is best understood as a convenience for effecting this frequent composition: 4mapsMPost phi = decompose . mapsPost (Compose . phi)The streaming prelude exports the same function under the better name  mappedPost., which overlaps with the lens libraries. linear-base A version of  that imposes a Control.Functor constraint on the target functor rather than the source functor. This version should be preferred if fmap& on the target functor is cheaper. linear-basefor replaces each element of a stream with an associated stream. Note that the associated stream may layer any control functor. linear-baseReplace each element in a stream of individual Haskell values (a Stream (Of a) m r) with an associated  functorial step. for str f = concats (with str f) with str f = for str (yields . f) with str f = maps (\(a:>r) -> r <$ f a) str with = flip subst subst = flip with >>> with (each' [1..3]) (yield . Prelude.show) & intercalates (yield "--") & S.stdoutLn 1 -- 2 -- 3  linear-baseReplace each element in a stream of individual values with a functorial layer of any sort. subst = flip with and is more convenient in a sequence of compositions that transform a stream. with = flip subst for str f = concats $ subst f str subst f = maps (\(a:>r) -> r <$ f a) S.concat = concats . subst each linear-baseDuplicate the content of a stream, so that it can be acted on twice in different ways, but without breaking streaming. Thus, with  each' [1,2] I might do: >>> S.print $ each' ["one","two"] "one" "two" >>> S.stdoutLn $ each' ["one","two"] one two )With copy, I can do these simultaneously: >>> S.print $ S.stdoutLn $ S.copy $ each' ["one","two"] "one" one "two" two $ should be understood together with effects and is subject to the rules ;S.effects . S.copy = id hoist S.effects . S.copy = idThe similar operations in wx obey the same rules.Where the actions you are contemplating are each simple folds over the elements, or a selection of elements, then the coupling of the folds is often more straightforwardly effected with yz , e.g. 9>>> L.purely S.fold (liftA2 (,) L.sum L.product) $ each'  55,36288001..10 :> ()  rather than >>> S.sum $ S.product . S.copy $ each' [1..10] 55 :> (3628800 :> ()) A  Control.Foldl fold can be altered to act on a selection of elements by using i{ on an appropriate lens. Some such manipulations are simpler and more |} -like, using : >>> L.purely S.fold (liftA2 (,) (L.handles (L.filtered odd) L.sum) (L.handles (L.filtered even) L.product)) $ each'  25,38401..10 :> () becomes >>> S.sum $ S.filter odd $ S.product $ S.filter even $ S.copy' $ each' [1..10] 25 :> (3840 :> ())  or using  >>> S.sum $ S.filter odd $ S.store (S.product . S.filter even) $ each' [1..10] 25 :> (3840 :> ()) But anything that fold of a Stream (Of a) m r into e.g. an  m (Of b r) that has a constraint on m that is carried over into  Stream f m - e.g.  Control.Monad, Control.Functor, etc. can be used on the stream. Thus, I can fold over different groupings of the original stream: >>> (S.toList . mapped S.toList . chunksOf 5) $ (S.toList . mapped S.toList . chunksOf 3) $ S.copy $ each' [1..10] [[1,2,3,4,5],[6,7,8,9,10]] :> ([[1,2,3],[4,5,6],[7,8,9],[10]] :> ()) The procedure can be iterated as one pleases, as one can see from this (otherwise unadvisable!) example: >>> (S.toList . mapped S.toList . chunksOf 4) $ (S.toList . mapped S.toList . chunksOf 3) $ S.copy $ (S.toList . mapped S.toList . chunksOf 2) $ S.copy $ each' [1..12] [[1,2,3,4],[5,6,7,8],[9,10,11,12]] :> ([[1,2,3],[4,5,6],[7,8,9],[10,11,12]] :> ([[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]] :> ())) copy% can be considered a special case of expand:  copy = expand# $ p (a :> as) -> a :> p (a :> as) If  were an instance of ~, then one could write  copy = expand extend  linear-base An alias for copy. linear-baseStore the result of any suitable fold over a stream, keeping the stream for further manipulation. store f = f . copy : >>> S.print $ S.store S.product $ each' [1..4] 1 2 3 4 24 :> ()  >>> S.print $ S.store S.sum $ S.store S.product $ each' [1..4] 1 2 3 4 10 :> (24 :> ()) Here the sum (10) and the product (24) have been 'stored' for use when finally we have traversed the stream with print . Needless to say, a second pass is excluded conceptually, so the folds that you apply successively with store are performed simultaneously, and in constant memory -- as they would be if, say, you linked them together with  Control.Fold: >>> L.impurely S.foldM (liftA3 (a b c -> (b, c)) (L.sink Prelude.print) (L.generalize L.sum) (L.generalize L.product)) $ each' [1..4] 1 2 3 4 (10,24) :> () "Fusing folds after the fashion of  Control.Foldl will generally be a bit faster than the corresponding succession of uses of , but by constant factor that will be completely dwarfed when any IO is at issue.But  /  is much more powerful, as you can see by reflecting on uses like this: >>> S.sum $ S.store (S.sum . mapped S.product . chunksOf 2) $ S.store (S.product . mapped S.sum . chunksOf 2) $ each' [1..6] 21 :> (44 :> (231 :> ())) It will be clear that this cannot be reproduced with any combination of lenses,  Control.Fold2 folds, or the like. (See also the discussion of .)It would conceivably be clearer to import a series of specializations of 2. It is intended to be used at types like this: storeM :: (forall s m . Control.Monad m => Stream (Of a) m s %1-> m (Of b s)) -> (Control.Monad n => Stream (Of a) n r %1-> Stream (Of a) n (Of b r)) storeM = storeIt is clear from this type that we are just using the general instance: instance (Control.Functor f, Control.Monad m) => Control.Monad (Stream f m)We thus can't be touching the elements of the stream, or the final return value. It is the same with other constraints that  Stream (Of a) inherits from the underlying monad. Thus I can independently filter and write to one file, but nub and write to another, or interact with a database and a logfile and the like: >>> (S.writeFile "hello2.txt" . S.nubOrd) $ store (S.writeFile "hello.txt" . S.filter (/= "world")) $ each' ["hello", "world", "goodbye", "world"] >>> :! cat hello.txt hello goodbye >>> :! cat hello2.txt hello world goodbye  linear-baseApply an action to all values, re-yielding each. The return value (y) of the function is ignored. >>> S.product $ S.chain Prelude.print $ S.each' [1..5] 1 2 3 4 5 120 :> ()  See also  for a variant of this which uses the return value of the function to transorm the values in the stream. linear-base Like the 8 but streaming. The result type is a stream of a's, but is not accumulated; the effects of the elements of the original stream are interleaved in the resulting stream. Compare: sequence :: Monad m => [m a] -> m [a] sequence :: Control.Monad m => Stream (Of (m a)) m r %1-> Stream (Of a) m r linear-base(Remove repeated elements from a Stream.  of course accumulates a  of elements that have already been seen and should thus be used with care. linear-baseUse 6 to have a custom ordering function for your elements. linear-base3More efficient versions of above when working with  s that use . linear-base/Skip elements of a stream that fail a predicate linear-base2Skip elements of a stream that fail a monadic test linear-base;Intersperse given value between each element of the stream. 7>>> S.print $ S.intersperse 0 $ each [1,2,3] 1 0 2 0 3  linear-baseIgnore the first n elements of a stream, but carry out the actions 2>>> S.toList $ S.drop 2 $ S.replicateM 5 getLine a Enter b Enter c Enter d Enter e Enter ["c","d","e"] :> () +Because it retains the final return value, drop n" is a suitable argument for maps: >>> S.toList $ concats $ maps (S.drop 4) $ chunksOf 5 $ each [1..20] [5,10,15,20] :> ()  linear-baseIgnore elements of a stream until a test succeeds, retaining the rest. 8>>> S.print $ S.dropWhile ((< 5) . length) S.stdinLn one Enter two Enter three Enter "three" four Enter "four" ^CInterrupted.  linear-baseStrict left scan, streaming, e.g. successive partial results. The seed is yielded first, before any action of finding the next element is performed. >>> S.print $ S.scan (++) "" id $ each' (words "a b c d") "" "a" "ab" "abc" "abcd"  is fitted for use with  Control.Foldl, thus: >>> S.print $ L.purely S.scan L.list $ each' [3..5] [] [3] [3,4] [3,4,5]  linear-baseStrict left scan, accepting a monadic function. It can be used with FoldMs from  Control.Foldl using impurely:. Here we yield a succession of vectors each recording >>> let v = L.impurely scanM L.vectorM $ each' [1..4::Int] :: Stream (Of (Vector Int)) IO () >>> S.print v [] [1] [1,2] [1,2,3] [1,2,3,4]  linear-baseLabel each element in a stream with a value accumulated according to a fold. +>>> S.print $ S.scanned (*) 1 id $ S.each'  100,100 100,200,300 (200,20000) (300,6000000) 5>>> S.print $ L.purely S.scanned' L.product $ S.each  100,100 100,200,300 (200,20000) (300,6000000)  linear-baseMake a stream of strings into a stream of parsed values, skipping bad cases >>> S.sum_ $ S.read $ S.takeWhile (/= "total") S.stdinLn :: IO Int 1000 Enter 2000 Enter total Enter 3000  linear-base0Interpolate a delay of n seconds between yields. linear-base The natural cons for a  Stream (Of a). )cons a stream = yield a Control.>> streamUseful for interoperation: Data.Text.foldr S.cons (return ()) :: Text -> Stream (Of Char) m () Lazy.foldrChunks S.cons (return ()) :: Lazy.ByteString -> Stream (Of Strict.ByteString) m () and so on. linear-baseBefore evaluating the monadic action returning the next step in the ,  wrapEffect1 extracts the value in a monadic computation m a and passes it to a computation a -> m y. linear-base accumulates the first n elements of a stream, update thereafter to form a sliding window of length n. It follows the behavior of the slidingWindow function in  https://hackage.haskell.org/package/conduit-combinators-1.0.4/docs/Data-Conduit-Combinators.html#v:slidingWindowconduit-combinators. >>> S.print $ S.slidingWindow 4 $ S.each "123456" fromList "1234" fromList "2345" fromList "3456" ; Safe-Inferred%&4. linear-baseWrite Strings to   using  ; terminates on a broken output pipe (The name and implementation are modelled on the  Pipes.Prelude stdoutLn).>>> withLinearIO $ Control.fmap move $ S.stdoutLn $ S.each $ words "one two three" one two three linear-base0Like stdoutLn but with an arbitrary return value linear-base-Print the elements of a stream as they arise. linear-base1Write a stream to a handle and return the handle. linear-base2Write a stream of text as lines as lines to a file linear-baseReduce a stream, performing its actions but ignoring its elements. >>> rest <- S.effects $ S.splitAt 2 $ each' [1..5] >>> S.print rest 3 4 5 $ should be understood together with  and is subject to the rules ;S.effects . S.copy = id hoist S.effects . S.copy = id The similar effects and copy operations in Data.ByteString.Streaming obey the same rules. linear-baseRemove the elements from a stream of values, retaining the structure of layers. linear-baseWhere a transformer returns a stream, run the effects of the stream, keeping the return value. This is usually used at the type drained :: Control.Monad m => Stream (Of a) m (Stream (Of b) m r) -> Stream (Of a) m r drained = Control.join . Control.fmap (Control.lift . effects)Here, for example, we split a stream in two places and throw out the middle segment: >>> rest <- S.print $ S.drained $ S.splitAt 2 $ S.splitAt 5 $ each' [1..7] 1 2 >>> S.print rest 6 7  linear-base:Reduce a stream to its return value with a monadic action. />>> S.mapM_ Prelude.print $ each' [1..3] 1 2 3 >>> rest <- S.mapM_ Prelude.print $ S.splitAt 3 $ each' [1..10] 1 2 3 >>> S.sum rest 49 :> ()  linear-baseStrict fold of a  of elements that preserves the return value. This does not short circuit and all effects are performed. The third parameter will often be  ! where a fold is written by hand: ->>> S.fold (+) 0 id $ each' [1..10] 55 :> ()  >>> S.fold (*) 1 id $ S.fold (+) 0 id $ S.copy $ each' [1..10] 3628800 :> (55 :> ()) It can be used to replace a standard Haskell type with one more suited to writing a strict accumulation function. It is also crucial to the Applicative instance for Control.Foldl.Fold We can apply such a fold purely Control.Foldl.purely S.fold :: Control.Monad m => Fold a b -> Stream (Of a) m r %1-> m (Of b r)Thus, specializing a bit: L.purely S.fold L.sum :: Stream (Of Int) Int r %1-> m (Of Int r) mapped (L.purely S.fold L.sum) :: Stream (Stream (Of Int)) IO r %1-> Stream (Of Int) IO r)Here we use the Applicative instance for Control.Foldl.Fold to stream three-item segments of a stream together with their sums and products. >>> S.print $ mapped (L.purely S.fold (liftA3 (,,) L.list L.product L.sum)) $ chunksOf 3 $ each'  [1,2,3],6,61..100 ([4,5,6],120,15) ([7,8,9],504,24) ([10],10,10)  linear-baseStrict fold of a  of elements, preserving only the result of the fold, not the return value of the stream. This does not short circuit and all effects are performed. The third parameter will often be  % where a fold is written by hand: '>>> S.fold_ (+) 0 id $ each [1..10] 55 It can be used to replace a standard Haskell type with one more suited to writing a strict accumulation function. It is also crucial to the Applicative instance for Control.Foldl.Fold Control.Foldl.purely fold :: Control.Monad m => Fold a b -> Stream (Of a) m () %1-> m b linear-base*Strict, monadic fold of the elements of a  Stream (Of a) Control.Foldl.impurely foldM :: Control.Monad m => FoldM a b -> Stream (Of a) m r %1-> m (b, r)Thus to accumulate the elements of a stream as a vector, together with a random element we might write: >>> L.impurely S.foldM (liftA2 (,) L.vectorM L.random) $ each' [1..10::Int] :: IO (Of (Vector Int, Maybe Int) ()) ([1,2,3,4,5,6,7,8,9,10],Just 9) :> ()  linear-base*Strict, monadic fold of the elements of a  Stream (Of a) Control.Foldl.impurely foldM_ :: Control.Monad m => FoldM a b -> Stream (Of a) m () %1-> m b linear-baseNote: does not short circuit linear-baseNote: does not short circuit linear-baseNote: does not short circuit linear-baseNote: does not short circuit linear-baseFold a 0 of numbers into their sum with the return value  mapped S.sum :: Stream (Stream (Of Int)) m r %1-> Stream (Of Int) m r #>>> S.sum $ each' [1..10] 55 :> () >>> (n :> rest) <- S.sum $ S.splitAt 3 $ each' [1..10] >>> System.IO.print n 6 >>> (m :> rest') <- S.sum $ S.splitAt 3 rest >>> System.IO.print m 15 >>> S.print rest' 7 8 9 10  linear-baseFold a  of numbers into their sum linear-baseFold a 4 of numbers into their product with the return value  mapped product :: Stream (Stream (Of Int)) m r -> Stream (Of Int) m r linear-baseFold a  of numbers into their product linear-base Note that  exhausts the rest of the stream following the first element, performing all monadic effects via  linear-base Note that  exhausts the rest of the stream following the first element, performing all monadic effects via  linear-base"Exhaust a stream deciding whether a was an element. linear-base6Run a stream, keeping its length and its return value. >>> S.print $ mapped S.length $ chunksOf 3 $ S.each' [1..10] 3 3 3 1  linear-base*Run a stream, remembering only its length: >>> runIdentity $ S.length_ (S.each [1..10] :: Stream (Of Int) Identity ()) 10  linear-baseConvert an effectful ' into a list alongside the return value  mapped toList :: Stream (Stream (Of a) m) m r %1-> Stream (Of [a]) m rLike ,  breaks streaming; unlike  it preserves the return value- and thus is frequently useful with e.g.  >>> S.print $ mapped S.toList $ chunksOf 3 $ each' [1..9] [1,2,3] [4,5,6] [7,8,9] >>> S.print $ mapped S.toList $ chunksOf 2 $ S.replicateM 4 getLine s Enter t Enter ["s","t"] u Enter v Enter ["u","v"]  linear-baseConvert an effectful  Stream (Of a) into a list of asNote: Needless to say, this function does not stream properly. It is basically the same as Prelude  which, like  replicateM,  and similar operations on traversable containers is a leading cause of space leaks. linear-base+Fold streamed items into their monoidal sum linear-baseA natural right fold for consuming a stream of elements. See also the more general iterT in the  Streaming' module and the still more general destroy linear-baseA natural right fold for consuming a stream of elements. See also the more general iterTM in the  Streaming' module and the still more general destroy ,foldrT (\a p -> Streaming.yield a >> p) = id)4 Safe-Inferred )*.4?Y  linear-base6An *affine stream is represented with a state of type x0, a possibly terminating step function of type (x %1-> m (Either (f x) r)), and a stop-short function  (x %1-> m r).+This mirrors the unfold of a normal stream: data Stream f m r where Stream :: x %1-> (x %1-> m (Either (f x) r)) -> Stream f m rThough referred to as an "affine stream" this might not be the correct definition for affine streams. Sorting this out requires a bit more careful thought. linear-baseA singleton stream #>>> stdoutLn $ yield "hello" hello 3>>> S.sum $ do {yield 1; yield 2; yield 3} 6 :> ()  linear-base2Stream the elements of a pure, foldable container. !>>> S.print $ each' [1..3] 1 2 3  linear-baseBuild a Stream by unfolding steps starting from a seed. In particular note that S.unfoldr S.next = id. linear-base,Read the lines of a file given the filename. linear-base Repeat an element several times. linear-base6Repeat an action several times, streaming its results. >>> import qualified Unsafe.Linear as Unsafe >>> import qualified Data.Time as Time >>> let getCurrentTime = fromSystemIO (Unsafe.coerce Time.getCurrentTime) >>> S.print $ S.replicateM 2 getCurrentTime 2015-08-18 00:57:36.124508 UTC 2015-08-18 00:57:36.124785 UTC  linear-baseReplicate a constant element and zip it with the finite stream which is the first argument.  linear-baseTake n> number of elements from the affine stream, for non-negative n . (Negative n is treated as 0.)  linear-baseRun an affine stream until it ends or a monadic test succeeds. Drop the element it succeeds on.  linear-baseLike   but without the monadic test.  linear-base*Zip a finite stream with an affine stream.  linear-base)An affine stream of standard input lines.  linear-base>> S.print $ S.enumFromThenN 3 100 200 100 200 300  linear-baseA finite sequence of enumerable values at a fixed distance determined by the first and second values. The length is limited by zipping with a given finite stream, i.e., the first argument. linear-baseLike  but where the next element in the enumeration is just the successor succ n for a given enum n. linear-baseLike  but where the next element in the enumeration is just the successor succ n for a given enum n. Safe-Inferred%&4@ linear-baseRead an IORef (Maybe a)$ or a similar device until it reads Nothing. reread# provides convenient exit from the  io-streams library reread readIORef :: IORef (Maybe a) -> Stream (Of a) IO () reread Streams.read :: System.IO.Streams.InputStream a -> Stream (Of a) IO () Safe-Inferred %&)*4N linear-baseThe (liberal) remainder of zipping three streams. This has the downside that the possibility of three remainders is allowed, though it will never occur. linear-base$The remainder of zipping two streams linear-baseThe type +Data.List.unzip :: [(a,b)] -> ([a],[b])might lead us to expect Streaming.unzip :: Stream (Of (a,b)) m r -> Stream (Of a) m (Stream (Of b) m r)which would not stream, since it would have to accumulate the second stream (of bs). Of course,  Data.List  doesn't stream either.This unzip does stream, though of course you can spoil this by using e.g. : >>> let xs = Prelude.map (x -> (x, Prelude.show x)) [1..5 :: Int] >>> S.toList $ S.toList $ S.unzip (S.each' xs) ["1","2","3","4","5"] :> ([1,2,3,4,5] :> ()) >>> Prelude.unzip xs ([1,2,3,4,5],["1","2","3","4","5"]) Note the difference of order in the results. It may be of some use to think why. The first application of % was applied to a stream of integers: >>> :t S.unzip $ S.each' xs S.unzip $ S.each' xs :: Control.Monad m => Stream (Of Int) (Stream (Of String) m) () Like any fold, ) takes no notice of the monad of effects. toList :: Control.Monad m => Stream (Of a) m r %1-> m (Of [a] r)#In the case at hand (since I am in ghci) m = Stream (Of String) IO. So when I apply , I exhaust that stream of integers, folding it into a list: >>> :t S.toList $ S.unzip $ S.each' xs S.toList $ S.unzip $ S.each' xs :: Control.Monad m => Stream (Of String) m (Of [Int] ())  When I apply  to this/, I reduce everything to an ordinary action in IO#, and return a list of strings: >>> S.toList $ S.toList $ S.unzip (S.each' xs) ["1","2","3","4","5"] :> ([1,2,3,4,5] :> ()) , can be considered a special case of either unzips or expand:  unzip = unzips . maps2 (((a,b) :> x) -> Compose (a :> b :> x)) unzip = expand) $ p ((a,b) :> abs) -> b :> p (a :> abs)  linear-basezipWithR zips two streams applying a function along the way, keeping the remainder of zipping if there is one. Note. If two streams have the same length, but one needs to perform some effects to obtain the end-of-stream result, that stream is treated as a residual. linear-basezip zips two streams exhausing the remainder of the longer stream and consuming its effects. linear-basezipR8 zips two streams keeping the remainder if there is one. linear-baseLike zipWithR but with three streams. linear-baseLike zipWith but with three streams linear-baseLike zipR but with three streams. linear-baseLike zipR but with three streams.  linear-baseInternal function to consume a stream remainder to get the payload linear-base1Merge two streams of elements ordered with their   instance./The return values of both streams are returned. >>> S.print $ merge (each [1,3,5]) (each [2,4]) 1 2 3 4 5 ((), ())  linear-baseMerge two streams, ordering them by applying the given function to each element before comparing./The return values of both streams are returned. linear-baseMerge two streams, ordering the elements using the given comparison function./The return values of both streams are returned. Safe-InferredN Safe-Inferred%&4yI linear-baseyields is like lift for items in the streamed functor. It makes a singleton or one-layer succession. lift :: (Control.Monad m, Control.Functor f) => m r %1-> Stream f m r yields :: (Control.Monad m, Control.Functor f) => f r %1-> Stream f m rViewed in another light, it is like a functor-general version of yield: S.yield a = yields (a :> ()) linear-base$Wrap an effect that returns a stream effect = join . lift linear-base&Wrap a new layer of a stream. So, e.g. S.cons :: Control.Monad m => a -> Stream (Of a) m r %1-> Stream (Of a) m r S.cons a str = wrap (a :> str)and, recursively: S.each' :: Control.Monad m => [a] -> Stream (Of a) m () S.each' = foldr (\a b -> wrap (a :> b)) (return ())The two operations wrap :: (Control.Monad m, Control.Functor f) => f (Stream f m r) %1-> Stream f m r effect :: (Control.Monad m, Control.Functor f) => m (Stream f m r) %1-> Stream f m r7are fundamental. We can define the parallel operations yields and lift in terms of them yields :: (Control.Monad m, Control.Functor f) => f r %1-> Stream f m r yields = wrap . Control.fmap Control.return lift :: (Control.Monad m, Control.Functor f) => m r %1-> Stream f m r lift = effect . Control.fmap Control.return linear-baseRepeat a functorial layer, command or instruction a fixed number of times. linear-base replicatesM n repeats an effect containing a functorial layer, command or instruction n times. linear-base%Reflect a church-encoded stream; cp. GHC.Exts.build streamFold return_ effect_ step_ (streamBuild psi) = psi return_ effect_ step_ linear-base;Map layers of one functor to another with a transformation. +maps id = id maps f . maps g = maps (f . g) linear-base;Map layers of one functor to another with a transformation. mapsPost id = id mapsPost f . mapsPost g = mapsPost (f . g) mapsPost f = maps fmapsPost is essentially the same as , but it imposes a Control.Functor constraint on its target functor rather than its source functor. It should be preferred if  Control.fmap is cheaper for the target functor than for the source functor. linear-baseMap layers of one functor to another with a transformation involving the base monad.  is more fundamental than mapsM, which is best understood as a convenience for effecting this frequent composition: ,mapsM phi = decompose . maps (Compose . phi)The streaming prelude exports the same function under the better name mapped., which overlaps with the lens libraries. linear-baseMap layers of one functor to another with a transformation involving the base monad.  mapsMPost is essentially the same as , but it imposes a Control.Functor constraint on its target functor rather than its source functor. It should be preferred if  Control.fmap is cheaper for the target functor than for the source functor.mapsPost is more fundamental than  mapsMPost, which is best understood as a convenience for effecting this frequent composition: 4mapsMPost phi = decompose . mapsPost (Compose . phi)The streaming prelude exports the same function under the better name  mappedPost., which overlaps with the lens libraries. linear-baseMap layers of one functor to another with a transformation involving the base monad. This could be trivial, e.g. let noteBeginning text x = (fromSystemIO (System.putStrLn text)) Control.>> (Control.return x)"this is completely functor-generalmaps and mapped obey these rules: maps id = id mapped return = id maps f . maps g = maps (f . g) mapped f . mapped g = mapped (f <=< g) maps f . mapped g = mapped (fmap f . g) mapped f . maps g = mapped (f <=< fmap g)maps is more fundamental than mapped, which is best understood as a convenience for effecting this frequent composition: -mapped phi = decompose . maps (Compose . phi) linear-base A version of  that imposes a Control.Functor constraint on the target functor rather than the source functor. This version should be preferred if  Control.fmap& on the target functor is cheaper. linear-baseA less-efficient version of hoist that works properly even when its argument is not a monad morphism. linear-baseGroup layers in an alternating stream into adjoining sub-streams of one type or another. linear-baseInspect the first stage of a freely layered sequence. Compare  Pipes.next and the replica Streaming.Prelude.next. This is the uncons for the general . unfold inspect = id Streaming.Prelude.unfoldr StreamingPrelude.next = id linear-baseSplit a succession of layers after some number, returning a streaming or effectful pair.>>> rest <- S.print $ S.splitAt 1 $ each' [1..3] 1 >>> S.print rest 2 3 splitAt 0 = return (\stream -> splitAt n stream >>= splitAt m) = splitAt (m+n) Thus, e.g. >>> rest  -S.print $ (s - splitsAt 2 s >>= splitsAt 2) each' [1..5] 1 2 3 4 >>> S.print rest 5 linear-base=Break a stream into substreams each with n functorial layers.>>> S.print $ mapped S.sum $ chunksOf 2 $ each' [1,1,1,1,1] 2 2 1 linear-base*Dissolves the segmentation into layers of  Stream f m layers. linear-base=Interpolate a layer at each segment. This specializes to e.g. intercalates :: Stream f m () -> Stream (Stream f m) m r %1-> Stream f m r linear-baseGiven a stream on a sum of functors, make it a stream on the left functor, with the streaming on the other functor as the governing monad. This is useful for acting on one or the other functor with a fold, leaving the other material for another treatment. It generalizes kl , but actually streams properly.>>> let odd_even = S.maps (S.distinguish even) $ S.each' [1..10::Int] >>> :t separate odd_even separate odd_even :: Monad m => Stream (Of Int) (Stream (Of Int) m) ()Now, for example, it is convenient to fold on the left and right values separately:>>> S.toList $ S.toList $ separate odd_even [2,4,6,8,10] :> ([1,3,5,7,9] :> ())3Or we can write them to separate files or whatever:>>> S.writeFile "even.txt" . S.show $ S.writeFile "odd.txt" . S.show $ S.separate odd_even >>> :! cat even.txt 2 4 6 8 10 >>> :! cat odd.txt 1 3 5 7 9"Of course, in the special case of Stream (Of a) m r;, we can achieve the above effects more simply by using mn>>> S.toList . S.filter even $ S.toList . S.filter odd $ S.copy $ each [1..10::Int] [2,4,6,8,10] :> ([1,3,5,7,9] :> ())But  and  are functor-general. linear-base-Rearrange a succession of layers of the form Compose m (f x).we could as well define  decompose by mapsM: decompose = mapped getComposebut mapped is best understood as: -mapped phi = decompose . maps (Compose . phi)since maps and hoist are the really fundamental operations that preserve the shape of the stream: maps :: (Control.Monad m, Control.Functor f) => (forall x. f x %1-> g x) -> Stream f m r %1-> Stream g m r hoist :: (Control.Monad m, Control.Functor f) => (forall a. m a %1-> n a) -> Stream f m r %1-> Stream f n r linear-baseIf  had a Comonad instance, then we'd have copy = expand extendSee  for a version that requires a Control.Functor g instance instead. linear-baseIf  had a Comonad instance, then we'd have copy = expandPost extendSee  for a version that requires a Control.Functor f instance instead. linear-base.Map each layer to an effect, and run them all. linear-base7Run the effects in a stream that merely layers effects. linear-base reorders the arguments of  to be more akin to foldr It is more convenient to query in ghci to figure out what kind of 'algebra' you need to write.>>> :t streamFold Control.return Control.join (Control.Monad m, Control.Functor f) => (f (m a) %1-> m a) -> Stream f m a %1-> m a -- iterT>>> :t streamFold Control.return (Control.join . Control.lift) (Control.Monad m, Control.Monad (t m), Control.Functor f, Control.MonadTrans t) => (f (t m a) %1-> t m a) -> Stream f m a %1-> t m a -- iterTM>>> :t streamFold Control.return effect (Control.Monad m, Control.Functor f, Control.Functor g) => (f (Stream g m r) %1-> Stream g m r) -> Stream f m r %1-> Stream g m r>>> :t f -> streamFold Control.return effect (wrap . f) (Control.Monad m, Control.Functor f, Control.Functor g) => (f (Stream g m a) %1-> g (Stream g m a)) -> Stream f m a %1-> Stream g m a -- maps>>> :t f -> streamFold Control.return effect (effect . Control.fmap wrap . f) (Control.Monad m, Control.Functor f, Control.Functor g) => (f (Stream g m a) %1-> m (g (Stream g m a))) -> Stream f m a %1-> Stream g m a -- mapped  streamFold done eff construct = eff . iterT (Control.return . construct . Control.fmap eff) . Control.fmap done  linear-base(Specialized fold following the usage of Control.Monad.Trans.Free iterT alg = streamFold Control.return Control.join alg iterT alg = runIdentityT . iterTM (IdentityT . alg . Control.fmap runIdentityT) linear-base(Specialized fold following the usage of Control.Monad.Trans.Free iterTM alg = streamFold Control.return (Control.join . Control.lift) iterTM alg = iterT alg . hoist Control.lift linear-base-Map a stream to its church encoding; compare Data.List.foldr.  may be more efficient in some cases when applicable, but it is less safe.  destroy s construct eff done = eff . iterT (Control.return . construct . Control.fmap eff) . Control.fmap done $ s (( Safe-Inferred)*/4<F linear-base'Box a' is the abstract type of manually managed data. It can be used as part of data type definitions in order to store linked data structure off heap. See  Foreign.List and  Foreign.Pair in the examples% directory of the source repository. linear-base)Pools represent collections of values. A  can be -ed. This is a no-op: it does not deallocate the data in that pool. It cannot do so, because accessible values might still exist. Consuming a pool simply makes it impossible to add new data to the pool. linear-base/This is an easier way to create an instance of . It is a bit abusive to use a type class for this (after all, it almost never makes sense to use this as a constraint). But it works in practice.To use, define an instance of MkRepresentable  myType intermediateType& then declare the following instance: instance Representable  myType where {type AsKnown = AsKnown  intermediateType}And the default instance mechanism will create the appropriate  instance.Laws of : must be total3 may be partial, but must be total on the image of  ofRepr . toRepr = id linear-baseLaws of : must be total3 may be partial, but must be total on the image of  ofKnown . toKnown == id linear-baseThis abstract type class represents values natively known to have a GC-less implementation. Basically, these are sequences (represented as tuples) of base types. linear-baseGiven a linear computation that manages memory, run that computation. linear-baseStore a value a2 on the system heap that is not managed by the GC. linear-base0Retrieve the value stored on system heap memory.       Safe-Inferred   Safe-Inferred4E linear-baseThe Bifunctor classLawsIf  is supplied, then    = If  and  are supplied, then    D    D  If all are supplied, then @ f g =  f   g Safe-Inferred4 linear-baseA SymmetricMonoidal classThis allows you to shuffle around a bifunctor nested in itself and swap the places of the two types held in the bifunctor. For instance, for tuples: You can use "lassoc :: (a,(b,c)) %1-> ((a,b),c) and then use  to access the aYou can use the dual, i.e., # rassoc :: ((a,b),c) %1-> (a,(b,c)) and then .You can swap the first and second values with swap :: (a,b) %1-> (b,a)Laws swap . swap = id rassoc . lassoc = id lassoc . rassoc = id :second swap . rassoc . first swap = rassoc . swap . rassoc Safe-Inferred4 Safe-Inferred4F linear-baseA market is a pair of constructor and deconstructor functions that encode a prism; a Market a b s t is equivalent to a  Prism a b s t. linear-baseAn exchange is a pair of translation functions that encode an isomorphism; an Exchange a b s t is equivalent to a  Iso a b s t. linear-baseA  Wandering arr instance means that there is a wander function which is the traversable generalization of the classic lens function: /forall f. Functor f => (a -> f b) -> (s -> f t)in our notation: forall arr. (HasKleisliFunctor arr) => (a `arr` b) -> (s `arr` t)wander specializes the Functor% constraint to a control applicative: forall f. Applicative f => (a -> f b) -> (s -> f t) forall arr. (HasKleisliApplicative arr) => (a `arr` b) -> (s `arr` t)where HasKleisliFunctor or HasKleisliApplicative+ are some constraints which allow for the arr to be  Kleisli f' for control functors or applicatives f. linear-base+Equivalently but less efficient in general: :wander :: Data.Traversable f => a `arr` b -> f a `arr` f b linear-baseA (Strong m u arr)6 instance means that the function-like thing of type a arr b/ can be extended to pass along a value of type c* as a constant via the bifunctor of type m.This typeclass is used primarily to generalize common patterns and instances that are defined when defining optics. The two uses below are used in defining lenses and prisms respectively in Control.Optics.Linear.Internal:If m is the tuple type constructor (,)3 then we can create a function-like thing of type (a,c) arr (b,c) passing along c as a constant.If m is Either3 then we can create a function-like thing of type  Either a c arr Either b c that either does the original function or behaves like the constant function. linear-baseA (Monoidal m u arr) is a profunctor arr+ that can be sequenced with the bifunctor m. In rough terms, you can combine two function-like things to one function-like thing that holds both input and output types with the bifunctor m. linear-baseA Profunctor can be thought of as a computation that involves taking a(s) as input and returning b(s). These computations compose with (linear) functions. Profunctors generalize the function arrow ->. Hence, think of a value of type x arr y for profunctor arr' to be something like a function from x to y.Laws: lmap id = id lmap (f . g) = lmap f . lmap g rmap id = id rmap (f . g) = rmap f . rmap g3 Safe-Inferred4 linear-base)Linear co-Kleisli arrows for the comonad w3. These arrows are still useful in the case where w is not a comonad however, and some profunctorial properties still hold in this weaker setting. However stronger requirements on f are needed for profunctorial strength, so we have fewer instances. linear-base$Linear Kleisli arrows for the monad m3. These arrows are still useful in the case where m is not a monad however, and some profunctorial properties still hold in this weaker setting. Safe-Inferred /4  linear-baseLinearly typed patch for the newtype deconstructor. (Temporary until inference will get this from the newtype declaration.))  9  Safe-InferredN    Safe-Inferred  ! Safe-Inferred4" Safe-InferredK# Safe-Inferred'$ Safe-Inferred4~ linear-baseLike O0 but allows to lift both linear and non-linear   actions into a linear monad. Safe-Inferred)*4?  linear-baseA pull array is an array from which it is easy to extract elements, and this can be done in any order. The linear consumption of a pull array means each element is consumed exactly once, but the length can be accessed freely. linear-baseProduce a pull array of lenght 1 consisting of solely the given element. linear-base9zip [x1, ..., xn] [y1, ..., yn] = [(x1,y1), ..., (xn,yn)] Partial:4 `zip [x1,x2,...,xn] [y1,y2,...,yp]` is an error if n D p. linear-baseConcatenate two pull arrays. linear-baseCreates a pull array of given size, filled with the given element. linear-baseA right-fold of a pull array. linear-baseExtract the length of an array, and give back the original array. linear-base arrIndexer len+ constructs a pull array given a function  arrIndexer that goes from an array index to array values and a specified length len. linear-base#This is a convenience function for alloc . transfer linear-base n v = (vl, vr) such that vl has length n. is total: if n is larger than the length of v, then vr is empty. linear-baseReverse a pull array. linear-base,Index a pull array (without checking bounds)  % Safe-Inferred4o linear-base!Convert a pull array into a list. linear-basezipWith f [x1,x2,...,xn] [y1,y2,...,yn] = [f x1 y1, ..., f xn yn] Partial:; `zipWith f [x1,x2,...,xn] [y1,y2,...,yp]` is an error if n D p. linear-base!Fold a pull array using a monoid. linear-base!Convert a Vector to a pull array.& Safe-Inferred 04  linear-baseA mutable array holding as linear-baseExtract the underlying  , consuming the  in process. linear-base Consume an .!Note that we can not implement a  instance because  is unlifted. linear-base=Allocate a mutable array of given size using a default value. The size should be non-negative. linear-baseAllocate a mutable array of given size using a default value, using another  as a uniqueness proof. The size should be non-negative. linear-baseCopy the first mutable array into the second mutable array, starting from the given index of the source array.It copies fewer elements if the second array is smaller than the first. n should be within [0..size src).  copyInto n src dest: dest[i] = src[n+i] for i < size dest, i < size src + n  linear-base)Return the array elements as a lazy list. linear-baseO(1) Convert an  to an immutable  . linear-baseClone an array.  0 Safe-Inferred )*24 linear-baseAllocate a constant array given a size and an initial value The size must be non-negative, otherwise this errors. linear-baseAllocate a constant array given a size and an initial value, using another array as a uniqueness proof. linear-baseAllocate an array from a list linear-baseSets the value of an index. The index should be less than the arrays size, otherwise this errors. linear-baseSame as , but does not do bounds-checking. The behaviour is undefined if an out-of-bounds index is provided. linear-baseGet the value of an index. The index should be less than the arrays , otherwise this errors. linear-baseSame as , but does not do bounds-checking. The behaviour is undefined if an out-of-bounds index is provided. linear-baseResize an array. That is, given an array, a target size, and a seed value; resize the array to the given size using the seed value to fill in the new cells when necessary and copying over all the unchanged cells.#Target size should be non-negative. let b = resize n x a, then size b = n, and b[i] = a[i] for i < size a, and b[i] = x for size a <= i < n.  linear-base)Return the array elements as a lazy list. linear-baseCopy a slice of the array, starting from given offset and copying given number of elements. Returns the pair (oldArray, slice).Start offset + target size should be within the input array, and both should be non-negative. let b = slice i n a, then size b = n, and b[j] = a[i+j] for 0 <= j < n  linear-baseO(1) Convert an  to an immutable   (from vector package). linear-baseSame as , but takes the  as the first parameter. linear-baseSame as , but takes the  as the first parameter. linear-baseSame as , but takes the  as the first parameter. linear-baseSame as , but takes the  as the first parameter.  linear-base:Check if given index is within the Array, otherwise panic. linear-base Start offset linear-base Target size ' Safe-Inferred4- Safe-Inferred )*4F linear-baseA dynamic mutable vector.  linear-base Current size  linear-baseWhen growing the vector, capacity will be multiplied by this number.This is usually chosen between 1.5 and 2; 2 being the most common.  linear-base Create a  from an . Result will have the size and capacity equal to the size of the given array."This is a constant time operation. linear-baseAllocate a constant vector of a given non-negative size (and error on a bad size) linear-baseAllocator from a list linear-base%Number of elements inside the vector.This might be different than how much actual memory the vector is using. For that, see: . linear-baseCapacity of a vector. In other words, the number of elements the vector can contain before it is copied to a bigger array. linear-baseInsert at the end of the vector. This will grow the vector if there is no empty space. linear-basePop from the end of the vector. This will never shrink the vector, use  to remove the wasted space. linear-baseWrite to an element . Note: this will not write to elements beyond the current size of the vector and will error instead. linear-baseSame as , but does not do bounds-checking. The behaviour is undefined when passed an invalid index. linear-baseRead from a vector, with an in-range index and error for an index that is out of range (with the usual range  0..size-1). linear-baseSame as , but does not do bounds-checking. The behaviour is undefined when passed an invalid index.  linear-baseSame as ", but does not do bounds-checking. linear-baseModify a value inside a vector, with an ability to return an extra information. Errors if the index is out of bounds. linear-baseSame as 6, but without the ability to return extra information. linear-base*Return the vector elements as a lazy list. linear-baseFilters the vector in-place. It does not deallocate unused capacity, use  for that if necessary. linear-base A version of fmap which can throw out elements. linear-baseResize the vector to not have any wasted memory (size == capacity). This returns a semantically identical vector. linear-baseReturn a slice of the vector with given size, starting from an offset.Start offset + target size should be within the input vector, and both should be non-negative.This is a constant time operation if the start offset is 0. Use 3 to remove the possible wasted space if necessary. linear-baseO(1) Convert a  to an immutable   (from vector package). linear-baseSame as , but takes the  as the first parameter. linear-baseSame as  unsafeSafe, but takes the  as the first parameter. linear-baseSame as , but takes the  as the first parameter. linear-baseSame as , but takes the  as the first parameter.  linear-baseGrows the vector to the closest power of growthFactor to fit at least n more elements.  linear-baseResize the vector to a non-negative size. In-range elements are preserved, the possible new elements are bottoms.  linear-base;Check if given index is within the Vector, otherwise panic.  linear-base?Underlying array (has size equal to or larger than the vectors)   ( Safe-Inferred Safe-Inferred)*/24v&  linear-base3The results of searching for where to insert a key.PSL's on the constructors are the probes spent from the query, this might be different than PSL's of the cell at the returned index (in case of   constructor).  linear-base8An empty cell at index to insert a new element with PSL.  linear-base:A matching cell at index with a PSL and a value to update.  linear-baseAn occupied, richer, cell which should be evicted when inserting the new element. The swapped-out cell will then need to be inserted with a higher PSL. linear-baseWhen resizing, the capacity will be multiplied by this amount. This should be greater than one. linear-base Run a computation with an empty  with given capacity.  linear-base=Create an empty HashMap, using another as a uniqueness proof. linear-baseRun a computation with an " containing given key-value pairs. linear-baseThe most general modification function; which can insert, update or delete a value of the key, while collecting an effect in the form of an arbitrary . linear-baseA general modification function; which can insert, update or delete a value of the key. See $, for an even more general function. linear-baseInsert a key value pair to a 1. It overwrites the previous value if it exists. linear-baseDelete a key from a *. Does nothing if the key does not exist. linear-base (in the provided order) the given key-value pairs to the hashmap. linear-base A version of fmap" which can throw out the elements.Complexity: O(capacity hm) linear-baseSame as ", but also has access to the keys. linear-baseComplexity: O(capacity hm) linear-baseComplexity: O(capacity hm) linear-base;Union of two maps using the provided function on conflicts.-Complexity: O(min(capacity hm1, capacity hm2) linear-baseA right-biased union.-Complexity: O(min(capacity hm1, capacity hm2) linear-base to decrease wasted memory. Returns a semantically identical .+This is only useful after a lot of deletes.Complexity: O(capacity hm) linear-base%Number of key-value pairs inside the  linear-baseMaximum number of elements the HashMap can store without resizing. However, for performance reasons, the  might be before full.Use  to reduce the wasted space. linear-baseLook up a value from a . linear-baseCheck if the given key exists. linear-base"Converts a HashMap to a lazy list.  linear-baseGiven a key, psl of the probe so far, current unread index, and a full hashmap, return a probe result: the place the key already exists, a place to swap from, or an unfilled cell to write over.  linear-baseTry to insert at a given index with a given PSL. So the probing starts from the given index (with the given PSL).  linear-baseShift all cells with PSLs > 0 in a continuous segment following the deleted cell, backwards by one and decrement their PSLs.  linear-baseMakes sure that the map is not exceeding its utilization threshold (constMaxUtilization), resizes (constGrowthFactor) if necessary.  linear-base&Resizes the HashMap to given capacity.Invariant: Given capacity should be greater than the size, this is not checked.  linear-base(The number of stored (key, value) pairs. linear-base.Capacity of the underlying array (cached here) linear-baseUnderlying array..     ) Safe-Inferred Safe-Inferred )*/4΅  * Safe-Inferred   Safe-Inferred)*4 linear-baseA destination array, or DArray, is a write-only array that is filled by some computation which ultimately returns an array. linear-base$Get the size of a destination array. linear-base(Fill a destination array with a constant linear-base fill a dest0 fills a singleton destination array. Caution,  a dest will fail is dest isn't of length exactly one. linear-basedropEmpty dest. consumes and empty array and fails otherwise. linear-base n dest = (destl, destr) such as destl has length n. is total: if n is larger than the length of dest, then destr is empty. linear-base>Fills the destination array with the contents of given vector.Errors if the given vector is smaller than the destination array. linear-baseFill a destination array using the given index-to-value function.  + Safe-Inferred  , Safe-Inferred)*4? linear-basePush arrays are un-allocated finished arrays. These are finished computations passed along or enlarged until we are ready to allocate. linear-baseConvert a push array into a vector by allocating. This would be a common end to a computation using push and pull arrays. linear-base x n) creates a constant push array of length n in which every element is x.  - Safe-Inferred4 linear-baseConvert a pull array into a push array. NOTE: this does NOT require allocation and can be in-lined. linear-base-This is a shortcut convenience function for transfer . Pull.fromVector. bkkkFFFFFFbbbbbbbbbbbb__^^........     21212224444444444;;;;;;;;;;;;;0<<<===8======BB/BBBBBBBBB0BBBBBBCOCOCCCGCCHEHHsHJJJJNJKAKKKL?LMMMMMMAMMMMMMMMMNMMMMMMPQQR|R|SSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTUUUUUWWWXWWWWWWWW[[[@[@\\\]]]]]]]]l`                                                     aaaaaacadaaaaaaaaeafaaaaagggggghhhhhphhqhhhhhohhhhhhhhhhlhh`hhhhuhhhvhhhhhhnhhhhhhhhhhhhhhhhhhhhhhrPtsuv$$$$$p%%%%&&&&&&&&&&&t&&8tt``ttp,,,,,,,,,,,,,,,,,,-- 4477777777;;;<<<==BGCHKKLLSVVVVVVVVVVWaaaaaah_  (linear-base-0.4.0-INifdktDXX9C2vI0Gst1y5Prelude.LinearData.Bool.LinearData.Maybe.LinearData.Ord.LinearData.Either.LinearData.Monoid.LinearSystem.IO.Resource.LinearData.Functor.LinearData.List.LinearData.Arity.LinearData.Tuple.Linear.CompatPrelude.Linear.GenericUtilData.Unrestricted.Linear#Prelude.Linear.Internal.GenericallyPrelude.Linear.GenericallyData.Tuple.LinearData.Replicator.LinearPrelude.Linear.Unsatisfiable Unsafe.Linear Data.V.LinearControl.Functor.LinearData.Num.LinearSystem.IO.LinearDebug.Trace.LinearStreaming.Prelude.LinearStreaming.LinearForeign.Marshal.PureData.Bifunctor.LinearData.Profunctor.LinearData.Profunctor.Kleisli.LinearControl.Optics.Linear.TraversalControl.Optics.Linear.PrismControl.Optics.Linear.LensControl.Optics.Linear.IsoControl.Optics.LinearControl.Monad.IO.Class.LinearData.Array.Polarized.Pull"Data.Array.Mutable.Unlifted.LinearData.Array.Mutable.LinearData.Vector.Mutable.LinearData.HashMap.Mutable.LinearData.Set.Mutable.LinearData.Array.DestinationData.Array.Polarized.PushData.Array.PolarizedData.Arity.Linear.InternalArityVelimUr$Data.Unrestricted.Linear.Internal.UrPrelude.Linear.Internal.TypeEqPrelude.Linear.Internal Data.KindType1Data.Replicator.Linear.Internal.ReplicationStreamdup2Data.ReplicatorLinearData.Replicator.Linear.Internal,Data.Unrestricted.Linear.Internal.Consumable)Data.Unrestricted.Linear.Internal.DupableData.UnrestrictedMovable AsMovable ApplicativeData.V.Linear.Internal%Data.Monoid.Linear.Internal.SemigroupPreludeMonoidData.Semigroup Semigroup"Data.Monoid.Linear.Internal.Monoid Data.Monoid$Data.Functor.Linear.Internal.Functor(Data.Functor.Linear.Internal.Applicative)Data.Unrestricted.Linear.Internal.Movable%Control.Functor.Linear.Internal.Class<$ NonLinearfoldM*Control.Functor.Linear.Internal.MonadTrans)Control.Functor.Linear.Internal.Instances%Control.Functor.Linear.Internal.State&Control.Functor.Linear.Internal.Reader%Data.Unrestricted.Linear.Internal.UrT#Control.Functor.Linear.Internal.Kan(Data.Functor.Linear.Internal.Traversabletraverse Data.V.Linear.Internal.Instances)Data.Replicator.Linear.Internal.Instances+Data.Unrestricted.Linear.Internal.InstancesData.Ord.Linear.Internal.EqData.Ord.Linear.Internal.OrdProductSummapMaybe"System.IO.Resource.Linear.Internal System.IOopenFileopenBinaryFilehSeekhTellStreaming.Linear.Internal.Type!Streaming.Linear.Internal.Process Control.Foldlpurely Data.EitherpartitionEithersStreaming.PreludecopygroupsplitbreaksfoldmconcattoListmapsmappedData.ByteString StreamingControlFoldlhandlesDataListControl.ComonadComonad Data.ListsequenceData.SetSet Data.IntSetIntSet!Streaming.Linear.Internal.Consume!Streaming.Linear.Internal.Produce!Streaming.Linear.Internal.InteropStreaming.Linear.Internal.ManyunzipForeign.Marshal.Pure.Internal(Data.Bifunctor.Linear.Internal.Bifunctor0Data.Bifunctor.Linear.Internal.SymmetricMonoidalControl.Optics.Linear.InternalMonadIO"Data.Array.Polarized.Pull.Internal"Data.Array.Mutable.Linear.Internal#Data.Vector.Mutable.Linear.Internal$Data.HashMap.Mutable.Linear.Internal Data.Set.Mutable.Linear.InternalData.Array.Destination.Internalbaseprint Data.TuplefstsndGHC.Base otherwiseGHC.Real fromRationalGHC.EnumenumFrom enumFromThen enumFromToenumFromThenTo fromIntegral realToFrac toInteger toRationalBoundedEnum GHC.FloatFloating FractionalIntegralGHC.ReadReadReal RealFloatRealFracGHC.ShowShowghc-prim GHC.TypesBoolCharDoubleFloatInt ghc-bignumGHC.Num.IntegerInteger GHC.MaybeMaybeOrderingRationalIOWordEitherFalseNothingJustTrueLeftRightLTEQGTmaxBoundminBoundgetLastLastgetFirstFirst writeFilereadLnreadIOreadFileputStrLnputStrputCharinteractgetLine getContentsgetChar appendFile GHC.IO.Device SeekFromEnd RelativeSeek AbsoluteSeekSeekModeGHC.IOFilePathData.Functor.ConstgetConstConst Data.Foldablenullfind Data.OldListsortOnsortinsertData.Semigroup.InternalgetSum getProductgetDualDualgetAnyAnygetAllAll Text.Readreadsread GHC.IO.IOMode WriteMode ReadWriteModeReadMode AppendModeIOMode readsPrecreadList readParenlexText.ParserCombinators.ReadPReadS significand scaleFloatisNegativeZeroisNaN isInfiniteisIEEEisDenormalized floatRange floatRadix floatDigitsexponent encodeFloat decodeFloatatan2tanhtansqrtsinhsinpilogBaselogexpcoshcosatanhatanasinhasinacoshacos**truncateroundproperFractionfloorceilingremquotRemquotmoddivModdivrecip/oddlcmgcdeven^^^toEnumsuccpredfromEnumShowS showsPrecshowListshowshows showString showParenshowCharGHC.ListtaillookuplastinitheadGHC.NumsubtractuntilGHC.Err undefinederrorWithoutStackTraceerrorIsFunNArityFunN PeanoToNat NatToPeanoPeanoZS&&||notunSolomkSoloRemoveMetaDataFixupMetaData1 FixupMetaDataunurliftlift2 Generically1 Generically unGenericallyunGenerically1$&idconstseq$!curryuncurry.forgetElim Replicatorconsume duplicatemappure<*>nextnext#takeextractextend UnsatisfiableBottom unsatisfiable ToLinearNunsafeLinearityProofNcoercetoLinear toLinear2 toLinear3 toLinearN$fToLinearN'repSxy$fToLinearN'repZab$fToLinearNBoxedRepnfg ConsumablelseqDupabledupRdup3dup4dup5dup6dup7dupMakeVemptyuncons#unconsconsmake theLengthfromReplicatordupVswapEndo<>appEndomemptymappendFunctorfmap<$>voidliftA2move MonadFailfailMonad>>=>>dataFmapDefault<&>dataPureDefaultreturnjoinap MonadTransStateStateTgetputgets runStateTstaterunState mapStateT withStateT execStateT evalStateTmapState withState execState evalStatemodifyReaderReaderT runReaderTask withReaderTlocalreader runReader mapReader mapReaderT withReaderasksUrTrunUrTliftUrTevalUrT GTraversable TraversablemapM sequenceAforforM mapAccumL mapAccumRgenericTraverse MovableMonoidEq==/=Ordcompare<=<>>=maxmineitherleftsrightsfromLeft fromRightmaybe fromMaybe maybeToList catMaybes MultiplyingAddingNumabssignum FromInteger fromIntegerRingSemiring MultIdentityoneMultiplicative* AdditiveGroupnegate- AddIdentityzeroAdditive+getAdded getMultiplied$fSemigroupSum $fMonoidSum$fSemigroupProduct$fMonoidProduct$fNumMovableNum$fFromIntegerMovableNum$fRingMovableNum$fSemiringMovableNum$fMultIdentityMovableNum$fMultiplicativeMovableNum$fAdditiveGroupMovableNum$fAddIdentityMovableNum$fAdditiveMovableNum$fMonoidAdding$fSemigroupAdding$fMonoidMultiplying$fSemigroupMultiplying$fEqMultiplying$fOrdMultiplying$fShowMultiplying$fSemigroupMultiplying0$fMonoidMultiplying0 $fEqAdding $fOrdAdding $fShowAdding$fSemigroupAdding0$fMonoidAdding0$fConsumableMovableNum$fDupableMovableNum$fMovableMovableNum$fNumMovableNum0 $fNumDouble$fNumInt$fFromIntegerDouble$fFromIntegerInt $fRingDouble $fRingInt$fSemiringDouble $fSemiringInt$fMultIdentityDouble$fMultIdentityInt$fMultiplicativeDouble$fMultiplicativeInt$fAdditiveGroupDouble$fAdditiveGroupInt$fAddIdentityDouble$fAddIdentityInt$fAdditiveDouble $fAdditiveInt++filterreverselengthsplitAtspan partition takeWhile dropWhiledrop intersperse intercalate transpose traverse'foldrfoldr1foldlfoldl'foldl1foldl1'foldMapfoldMap'concat concatMapsumproductanyallandoriteraterepeatcyclescanlscanl1scanrscanr1 replicateunfoldrzipzip'zip3zipWithzipWith'zipWith3unzip3 $fMonoid[] $fSemigroup[]$fSemigroupNonEmptyflip<* fromSystemIO fromSystemIOU withLinearIOnewIORef readIORef writeIORefthrowIOcatchmask_ $fMonoidIO $fSemigroupIO $fMonadIO$fApplicativeIO $fFunctorIO $fFunctorIO0$fApplicativeIO0UnsafeResourceResourceHandleRIOrunhClosehIsEOFhGetCharhPutCharhGetLinehPutStr hPutStrLnrelease unsafeRelease unsafeAcquireunsafeFromSystemIOResourceunsafeFromSystemIOResource_trace traceShowtraceId traceStacktraceIOtraceM traceShowM traceEvent traceEventIO traceMarker traceMarkerIOOf:>StreamStepEffectReturndestroyExposedbreak breakWhen breakWhen'groupBy distinguishswitch sumToEither eitherToSum composeToSum sumToComposeseparate unseparate mapMaybeMhoistmapsPost mapsMPost mappedPostwithsubststorechainnubOrdnubOrdOnnubIntnubIntOnfilterMscanscanMscanneddelay wrapEffect slidingWindowstdoutLn stdoutLn'toHandleeffectserasedrainedmapM_fold_foldM_all_any_sum_product_head_last_elemelem_notElemnotElem_length_toList_mconcat_minimumminimum_maximummaximum_foldrMfoldrTyieldeach' fromHandle replicateM replicateZip untilRightstdinLnN stdinLnUntilM stdinLnUntil stdinLnZipreadLnN readLnUntilM readLnUntil readLnZipiterateN iterateZip iterateMN iterateMZipcycleNcycleZip enumFromThenNenumFromThenZip enumFromN enumFromZipreread ZipResidual3 ZipResidualEither3Left3Middle3Right3zipWithRzipR zipWith3Rzip3RmergemergeOnmergeByyieldseffectwrap replicates replicatesMunfold untilJust streamBuilddelaysmapsMhoistUnexposedgroupsinspectsplitsAtchunksOfconcats intercalatesunzips decomposeexpand expandPostmapsM_ streamFolditerTiterTMdestroyBoxPoolMkRepresentabletoReprofRepr RepresentableAsKnowntoKnownofKnownKnownRepresentablewithPoolalloc deconstruct BifunctorbimapfirstsecondSymmetricMonoidalrassoclassocMarketExchange WanderingwanderStrongMonoidal***unit Profunctordimaplmaprmap runMarket$fProfunctorKleisli$fProfunctorFUN$fProfunctorFUN0$fMonoidalEitherVoidKleisli$fMonoidal(,)()Kleisli$fMonoidalEitherVoidFUN$fMonoidal(,)()FUN$fMonoidalEitherVoidFUN0$fMonoidal(,)()FUN0$fStrongEitherVoidKleisli$fStrong(,)()Kleisli$fStrongEitherVoidFUN$fStrong(,)()FUN$fStrongEitherVoidFUN0$fStrong(,)()FUN0$fWanderingFUN$fProfunctorExchange$fStrongEitherVoidMarket$fProfunctorMarket CoKleisli runCoKleisliKleisli runKleisli$fWanderingKleisli$fStrongEitherVoidCoKleisli$fProfunctorCoKleisli Traversal' TraversalPrism'PrismLens'LensIso'IsoOpticOptic_Opticalassoc.>lensprism traversal_1_2_Left_Right_Just_Nothing traversedover traverseOfsetsetSwapmatchbuildoverU traverseOfUisowithIso withPrismwithLens reifyLensliftIO liftSystemIO liftSystemIOU $fMonadIOIOArray singletonappend findLength fromFunctiontoVectorindexasList fromVectorArray#unArray# allocBesidesizecopyIntofreezefromList unsafeSet unsafeGetresizeslicewrite unsafeWrite unsafeReadVectorconstantcapacitypushpopmodify_ shrinkToFitKeyedHashMapalterFalterdelete insertAllmapMaybeWithKey filterWithKey unionWithunionintersectionWithmember intersectionDArrayfill dropEmptymirrorsnoc $fMonoidArray$fMonoidArray0$fSemigroupArray$fSemigroupArray0$fFunctorArray$fMonoidArrayWriter$fSemigroupArrayWriter$fMonoidArrayWriter0$fSemigroupArrayWriter0transferwalk GHC.TypeNatsNat GHC.TupleSolo GHC.GenericsGeneric,linear-generics-0.2.2-7cAUO5HMNtK8HF9YGoKHKUGenerics.Linear.ClassGeneric1Datatype packageName moduleName datatypeName isNewtype ConstructorconName conFixity conIsRecordSelectorselSourceUnpackednessselSourceStrictnessselDecidedStrictnessselNameV1U1Par1unPar1K1unK1M1unM1:+:L1R1:*:RDCRec0D1C1S1URecuWord#uInt#uFloat#uDouble#uChar#uAddr#UAddrUCharUDoubleUFloatUWordUIntSourceUnpackedness SourceUnpackNoSourceUnpackednessSourceNoUnpackSourceStrictness SourceLazyNoSourceStrictness SourceStrictMetaMetaDataMetaSelMetaConsFixityIInfixIPrefixIFixityInfixPrefixDecidedStrictness DecidedLazy DecidedUnpack DecidedStrict AssociativityLeftAssociativeNotAssociativeRightAssociativeprecunMP1ReptofromRep1to1from1:.:Comp1unComp1MP1lcoerceGHC.Prim runIdentity'ReplicationStreamMovedStreamed ToLinearN'ToINatINat GConsumableseqUnitgenericConsumeGDupable genericDupR $fSemigroupUr $fMonoidUr genericPure genericLiftA2GMovable genericMovereplaceCurriedYoneda lowerCurriedC runYoneda runCurried lowerYonedaliftCurriedYonedaCyapStateR Data.StringIsString fromStringStringwordsunwordsunlineslines toSystemIOunsafeFromSystemIO ReleaseMapunRIOconsFirstChunkData.Functor.SumGHC.IO.StdHandlesstdout text-1.2.5.0 Data.Text.IO AffineStreamuntilMstdinLniterateM extractResult GHC.ClassesDLLpreveltstorableDict stripMaybe stripMaybePtrstripPtr insertAfterfreeAllreprPokereprNewreprPeek getConst'toListOflengthOf MutableArray#%vector-0.13.1.0-2lCeeCyC2I3KCSVrGQfe2 Data.VectorassertIndexInRangeVecconstGrowthFactor fromArray unsafeModify growToFit unsafeResize ProbeResult IndexToSwap IndexToInsert IndexToUpdatePSLRobinValRobinArrconstMaxLoadFactor probeFromtryInsertAtIndexshiftSegmentBackwardgrowMapIfNecessaryincRobinValPSLdecRobinValPSL _debugShowidealIndexForKeychainUchainU'