έ [      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwx y z { | } ~         !"#$%&'()*+,-./0123456789 : ; < = > ? @ A B C D E F G H I J K L M N O PQRSTUVWXYZ(Core types, constructors, and utilities.(c) Justin Le 2015MIT justin@jle.imunstableportableNone0ALOT=Special case of  where the underlying [ is \.Instead of "wrapping" an  [a] -> m [b], it "wraps" an  [a] -> [b].The  type. For this library, an  semantically represents denotes a a relationship/ between an input and an output that is preserved over multiple steps, where that relationship is (optionally) maintained within the context of a monad.7A lot of fancy words, I know...but you can think of an  as nothing more than a "stream transformer" of value streams. A stream of sequential input values come in one at a time, and a stream of outputs pop out one at a time, as well. Using the  streamAutoI function, you can "unwrap" the inner value stream transformer from any : if a ::  m a b,  streamAuto lets you turn it into an  [a] -> m [b]. "Give me a stream of a/s, one at a time, and I'll give you a list of b.s, matching a relationship to your stream of as." #-- unwrap your inner [a] -> m [b]!  streamAuto :: Monad m =>  m a b -> ([a] -> m [b]) You can also turn an  m a b into an effects stream* that executes effects sequentially with toEffectStream and streamAutoEffects:, so you can run it with a ListT-compatible library like pipes.There's a handy type synonym B for relationships that don't really need a monadic context; the m is just \: type Auto' = Auto Identity So if you had an a ::  a b, you can use  streamAuto', to "unwrap" the inner stream transformer,  [a] -> [b]. !-- unwrap your inner [a] -> [b]!  streamAuto' ::  a b -> ([a] -> [b])  All of the s given in this library maintain some sort of semantic relationship between streams --- for some, the outputs might be the inputs with a function applied; for others, the outputs might be the cumulative sum of the inputs. See the  ?https://github.com/mstksg/auto/blob/master/tutorial/tutorial.mdtutorial for more information!Operationally, an  m a b? is implemented as a "stateful function". A function from an a. where, every time you "apply" it, you get a b and an "updated "/function with updated state. You can get this function using  :   ::  m a b -> (a -> m (b,  m a b)) Or, for , :  ::  a b -> (a -> (b,  a b))  "Give me an a and I'll give you a b and your "updated" ".~s really are mostly useful because they can be composed, chained, and modified using their various typeclass instances, like ], ^, _, `e, etc., and also with the combinators in this library. You can build complex programs as a complex a by building up smaller and smaller components. See the tutorial for more information on this.This type also contains information on its own serialization, so you can serialize and re-load the internal state to binary or disk. See the "serialization" section in the documentation for Control.Auto.Core, or the documentation for  for more details. Re-structure  internals to use the Arb@ ("arbitrary") constructors, as recursion-based mealy machines.BMostly here for performance comparisons and benchmarking purposes.DReturns a string representation of the internal constructor of the {. Useful for debugging the result of compositions and functions and seeing how they affect the internal structure of the .In the order of efficiency, AutoFuncs tend to be faster than  AutoStates tend to be faster than AutoArb7s. However, when composing one with the other (using ] or ^R), the two have to be "reduced" to the greatest common denominator; composing an AutoFunc with an AutoArb produces an AutoArb.gMore benchmarking is to be done to be able to rigorously say what these really mean, performance wise.Swaps out the underlying [ of an S using the given monad morphism "transforming function", a natural transformation..Basically, given a function to "swap out" any m a with an m' a,, it swaps out the underlying monad of the .>This forms a functor, so you rest assured in things like this: @hoistA id == id hoistA f a1 . hoistA f a2 == hoistA f (a1 . a2) Generalizes an  a b to an  m a b' for any [ m, using hoist.RYou generally should be able to avoid using this if you never directly write any 4s and always write 'Auto m' parameterized over all [Os, but...in case you import one from a library or something, you can use this.'Force the serializing components of an .TODO: Test if this really works Encode an  and its internal state into a a. Resume an  from its a serialization, giving a b( if the deserialization is not possible.  Returns a c from an  --- instructions (from Data.Serialize?) on taking a ByteString and "restoring" the originally saved  , in the originally saved state.  Returns a d --- instructions (from Data.Serialize) on how to "freeze" the j, with its internal state, and save it to a binary encoding. It can later be reloaded and "resumed" by 'resumeAuto'/'decodeAuto'.  Takes an / that is serializable/resumable and returns an  that is not. That is, when it is "saved", saves no data, and when it is "resumed", resets itself back to the initial configuration every time; in other words,  , (unserialize a) bs = Right (unserialize a)A. Trying to "resume" it will just always give itself, unchanged. Runs the  through one step.That is, given an  m a b#, returns a function that takes an a and returns a b and an "updated"/"next" ; an  a -> m (b,  m a b).#This is the main way of running an  "step by step", so if you have some sort of game loop that updates everything every "tick", this is what you're looking for. At every loop, gather input a, feed it into the , "render" the result b, and get your new  to run the next time.Here is an example with sumFrom 0, the N whose output is the cumulative sum of the inputs, and an underying monad of Identity. Here, ]stepAuto :: Auto Identity Int Int -> (Int -> Identity (Int, Auto Identity Int Int)) &Every time you "step", you give it an e and get a resulting e( (the cumulative sum) and the "updated !", with the updated accumulator.let a0 :: Auto Identity Int Int a0 = sumFrom 0:let Identity (res1, a1) = stepAuto a0 4 -- run with 4res1)4 -- the cumulative sum, 4:let Identity (res2, a2) = stepAuto a1 5 -- run with 5res2-9 -- the cumulative sum, 4 + 5:let Identity (res3, _ ) = stepAuto a2 3 -- run with 3res3112 -- the cumulative sum, 4 + 5 + 3$By the way, for the case where your  is under \, we have a type synomym E...and a convenience function to make "running" it more streamlined:let a0 :: Auto' Int Int a0 = sumFrom 06let (res1, a1) = stepAuto' a0 4 -- run with 4res1)4 -- the cumulative sum, 46let (res2, a2) = stepAuto' a1 5 -- run with 5res2-9 -- the cumulative sum, 4 + 56let (res3, _ ) = stepAuto' a2 3 -- run with 3res3112 -- the cumulative sum, 4 + 5 + 3 But, if your * actaully has effects when being stepped,   will execute them:let a0 :: Auto IO Int Int2 a0 = effect (putStrLn "hey!") *> sumFrom 06(res1, a1) <- stepAuto a0 4 -- run with 4hey! -- IO effectres1)4 -- the cumulative sum, 46(res2, a2) <- stepAuto a1 5 -- run with 5hey! -- IO effectres2-9 -- the cumulative sum, 4 + 56(res3, _ ) <- stepAuto a2 3 -- run with 3hey! -- IO effectres3112 -- the cumulative sum, 4 + 5 + 3(Here, effect (f "hey") is an  IO Int ()-, which ignores its input and just executes f "hey"% every time it is run. When we use g from Control.Applicative, we "combine" the two s together and run them botht on each input (4, 5, 3...)...but for the "final" output at the end, we only return the output of the second one, sumFrom 0 (5, 9, 12...))If you think of an  m a b as a "stateful function" a -> m b, then   lets you "run" it.In order to directly run an  on a stream, an [a], use  streamAuto. That gives you an  [a] -> m [b].Runs an  through one step.That is, given an  a b#, returns a function that takes an a and returns a b and an "updated"/"next" ; an  a -> (b,  a b).See  [ documentation for motivations, use cases, and more details. You can use this instead of   when your underyling monad is \ , and your  doesn't produce any effects.Here is an example with sumFrom 0, the 2 whose output is the cumulative sum of the inputs FstepAuto' :: Auto' Int Int -> (Int -> (Int, Auto' Int Int)) &Every time you "step", you give it an e and get a resulting e( (the cumulative sum) and the "updated !", with the updated accumulator.let a0 :: Auto' Int Int a0 = sumFrom 06let (res1, a1) = stepAuto' a0 4 -- run with 4res1)4 -- the cumulative sum, 46let (res2, a2) = stepAuto' a1 5 -- run with 5res2-9 -- the cumulative sum, 4 + 56let (res3, _ ) = stepAuto' a2 3 -- run with 3res3112 -- the cumulative sum, 4 + 5 + 3If you think of an  a b as a "stateful function" a -> b, then  lets you "run" it.In order to directly run an  on a stream, an [a], use  streamAuto'. That gives you an  [a] -> [b].In theory, "purifying" an 7" should prep it for faster evaluation when used with  or  streamAuto'<. But the benchmarks have not been run yet, so stay tuned!TODO: BenchmarkLike  , but drops the "next " and just gives the result.Like , but drops the "next " and just gives the result.  for .Like  4, but drops the result and just gives the "updated ".Like 4, but drops the result and just gives the "updated ".  for . A special  that acts like the h \, but forces results as they come through to be fully evaluated, when composed with other s.TODO: Test if this really works A special  that acts like the h Z, but forces results as they come through to be evaluated to Weak Head Normal Form, with i, when composed with other s.TODO: Test if this really works[Abstraction over lower-level funging with serialization; lets you modify the result of an  by being able to intercept the (b,  m a b)& output and return a new output value m c.Note that this is a lot like j: -fmap :: (b -> c) -> Auto m a b -> Auto m a c $Except gives you access to both the b and the "updated "; instead of an b -> c, you get to pass a (b,  m a b) -> m c.aBasically experimenting with a bunch of abstractions over different lower-level modification of Rs, because making sure the serialization works as planned can be a bit difficult. Construct an P by explicity giving its serialization, deserialization, and the function from a to a b and "updated ".Ideally, you wouldn't have to use this unless you are making your own framework. Try your best to make what you want by assembling primtives together. Working with serilization directly is hard.See 4 for more detailed instructions on doing this right. Construct an \ by explicitly giving its serializiation, deserialization, and the (monadic) function from a to a b and the "updated ".'See the "serialization" section in the Control.Auto.Core module for more information.Ideally, you wouldn't have to use this unless you are making your own framework. Try your best to make what you want by assembling primtives together.WBut sometimes you have to write your own combinators, and you're going to have to use  to make it work.Sometimes, it's simple: 0fmap :: (a -> b) -> Auto r a -> Auto r b fmap f a0 = mkAutoM (do aResumed <- resumeAuto a0 return (fmap f aResumed) ) (saveAuto a0) $ x -> do (y, a1) <- stepAuto a0 x return (f y, fmap f a1)  Serializing j f a0! is just the same as serializing a0 . And to resume it, we resume a0 to get a resumed version of a0, and then we apply j f to the  that we resumed.&Also another nice "simple" example is: catchA :: Exception e => Auto IO a b -> Auto IO a (Either e b) catchA a = mkAutoM (do aResumed <- resumeAuto a return (catchA aResumed) ) (saveAuto a) $ x -> do eya' <- try $ stepAuto a x case eya' of Right (y, a') -> return (Right y, catchA a') Left e -> return (Left e , catchA a ) XWhich is basically the same principle, in terms of serializing and resuming strategies.@When you have "switching" --- things that behave like different os at different points in time --- then things get a little complicated, because you have to figure out which  to resume.)For example, let's look at the source of -?>: U(-?>) :: Monad m => Interval m a b -- ^ initial behavior -> Interval m a b -- ^ final behavior, when the initial -- behavior turns off. -> Interval m a b a1 -?> a2 = mkAutoM l s t where l = do flag <- get if flag then resumeAuto (switched a2) else (-?> a2)  $ resumeAuto a1 s = put False *> saveAuto a1 t x = do (y1, a1') <- stepAuto a1 x case y1 of Just _ -> return (y1, a1' -?> a2) Nothing -> do (y, a2') <- stepAuto a2 x return (y, switched a2') switched a = mkAutoM l (put True *> saveAuto a) $ x -> do (y, a') <- stepAuto a x return (y, switched a') oWe have to invent a serialization and reloading scheme, taking into account the two states that the resulting  can be in: Initially, it is behaving like a1L. So, to save it, we put a flag saying that we are still in stage 1 (k), and then put a1's current serialization data.&After the switch, it is behaving like a2J. So, to save it, we put a flag saying that we are now in stage 2 (l), and then put a2 's current. Now, when we resume a1 -?> a2,   on a1 -?> a2 will give us l . So the c5 we use --- the process we use to resume the entire a1 -?> a2, will start at the initial c/loading function, lj here. We have to encode our branching and resuming/serialization scheme into the initial, front-facing l. So l has to check for the flag, and if the flag is true, load in the data for the switched state; otherwise, load in the data for the pre-switched state.Not all of them are this tricky. Mostly "switching" combinators will be tricky, because switching means changing what you are serializing.2This one might be considerably easier, because of m: izipAuto :: Monad m => a -- ^ default input value -> [Auto m a b] -- ^ Js to zip up -> Auto m [a] [b] zipAuto x0 as = mkAutoM (zipAuto x0  $ mapM resumeAuto as) (mapM_ saveAuto as) $ xs -> do res <- zipWithM stepAuto as (xs ++ repeat x0) let (ys, as') = unzip res return (ys, zipAuto x0 as') $To serialize, we basically sequence   over all of the internal _s --- serialize each of their serialization data one-by-one one after the other in our binary.0To load, we do the same thing; we go over every  in as and  C it, and then collect the results in a list --- a list of resumed s. And then we apply zipAuto x0 to that list of s, to get our resumed zipAuto x0 as.So, it might be complicated. In the end, it might be all worth it, too, to have implicit serialization compose like this. Think about your serialization strategy first. Step back and think about what you need to serialize at every step, and remember that it's _the initial_ "resuming" function that has to "resume everything"...it's not the resuming function that exists when you finally save your , it's the resuming c that was there at the beginning. For -?>, the intial l! had to know how to "skip ahead".And of course as always, test.If you need to make your own combinator or transformer but are having trouble with the serializtion, feel free to contact me at  justin@jle.im, on freenode at #haskell or  #haskell-auto , open a  %https://github.com/mstksg/auto/issues github issue8, etc. Just contact me somehow, I'll be happy to help!Like B, but without any way of meaningful serializing or deserializing.Be careful! This  can still carry arbitrary internal state, but it cannot be meaningfully serialized or re-loaded/resumed. You can still pretend to do so using 1'resumeAuto'/'saveAuto'/'encodeAuto'/'decodeAuto'h (and the type system won't stop you), but when you try to "resume"/decode it, its state will be lost.Like B, but without any way of meaningful serializing or deserializing.Be careful! This  can still carry arbitrary internal state, but it cannot be meaningfully serialized or re-loaded/resumed. You can still pretend to do so using 1'resumeAuto'/'saveAuto'/'encodeAuto'/'decodeAuto'i (and the type system won't stop you), but when you try to "resume"/decode it, its state will be reset.Construct the = whose output is always the given value, ignoring its input.;Provided for API constency, but you should really be using  from the ^ instance, from Control.Applicative, which does the same thing.Construct the y that always "executes" the given monadic value at every step, yielding the result as its output and ignoring its input.<Provided for API consistency, but you shold really be using effect from Control.Auto.Effects, which does the same thing.Construct a stateless  that simply applies the given (pure) function to every input, yielding the output. The output stream is just the result of applying the function to every input.streamAuto' (mkFunc f) = map f+This is rarely needed; you should be using n from the ` instance, from  Control.Arrow.Construct a stateless  that simply applies and executes the givne (monadic) function to every input, yielding the output. The output stream is the result of applying the function to every input, executing/sequencing the action, and returning the returned value.streamAuto (mkFuncM f) = mapM fIt's recommended that you use arrM from Control.Auto.Effects1. This is only really provided for consistency. Construct an  from a state transformer: an a -> s -> (b, s) gives you an  m a b , for any [ m#. At every step, it takes in the aG input, runs the function with the stored internal state, returns the bn result, and now contains the new resulting state. You have to intialize it with an initial state, of course.KFrom the "stream transformer" point of view, this is rougly equivalent to o from  Data.ListD, with the function's arguments and results in the backwards order.CstreamAuto' (mkState f s0) = snd . mapAccumL (\s x -> swap (f x s))Try not to use this if it's ever avoidable, unless you're a framework developer or something. Try make something by combining/composing the various  combinators.If your state s does not have a pl instance, then you should either write a meaningful one, provide the serialization methods manually with !), or throw away serializability and use #.  Construct an % from a "monadic" state transformer: a -> s -> m (b, s) gives you an  m a b#. At every step, it takes in the aM input, runs the function with the stored internal state and "executes" the m (b, s) to get the b output, and stores the sH as the new, updated state. Must be initialized with an initial state.Try not to use this if it's ever avoidable, unless you're a framework developer or something. Try make something by combining/composing the various  combinators.!This version is a wrapper around , that keeps track of the serialization and re-loading of the internal state for you, so you don't have to deal with it explicitly.If your state s does not have a pl instance, then you should either write a meaningful one, provide the serialization methods manually with "), or throw away serializability and use $.! A version of +, where the internal state doesn't have a pS instance, so you provide your own instructions for getting and putting the state.See  for more details." A version of  +, where the internal state doesn't have a pS instance, so you provide your own instructions for getting and putting the state.See   for more details.# A version of t, where the internal state isn't serialized. It can be "saved" and "loaded", but the state is lost in the process.See  for more details.Useful if your state s cannot have a meaningful p instance.$ A version of  s, where the internal state isn't serialized. It can be "saved" and "loaded", but the state is lost in the process.See   for more details.Useful if your state s cannot have a meaningful p instance.% Construct an  from a "folding" function:  b -> a -> b yields an  m a b. Basically acts like a q or a r?. There is an internal accumulator that is "updated" with an a6 at every step. Must be given an initial accumulator. Example: an  that sums up all of its input.let summer = accum (+) 0)let (sum1, summer') = stepAuto' summer 3sum13+let (sum2, summer'') = stepAuto' summer' 10sum213streamAuto' summer'' [1..10][14,16,19,23,28,34,41,49,58,68]If your accumulator b does not have a pb instance, then you should either write a meaningful one, or throw away serializability and use '.& Construct an & from a "monadic" "folding" function: b -> a -> m b yields an  m a b. Basically acts like a s or scanMU (if it existed). here is an internal accumulator that is "updated" with an input a! with the result of the executed m b7 at every step. Must be given an initial accumulator.See % for more details.If your accumulator b does not have a pb instance, then you should either write a meaningful one, or throw away serializability and use (.' A version of %z, where the internal accumulator isn't serialized. It can be "saved" and "loaded", but the state is lost in the process.See % for more details.Useful if your accumulator b cannot have a meaningful p instance.(A version of 'accumM_, where the internal accumulator isn't serialized. It can be "saved" and "loaded", but the state is lost in the process.See & for more details.Useful if your accumulator b cannot have a meaningful p instance.)A "delayed" version of %, where the first output is the initial state of the accumulator, before applying the folding function. Useful in recursive bindings.let summerD = accumD (+) 0+let (sum1, summerD') = stepAuto' summerD 3sum10-let (sum2, summerD'') = stepAuto' summerD' 10sum23streamAuto' summerD'' [1..10][13,14,16,19,23,28,34,41,49,58](Compare with the example in %).Note that this is more or less an encoding of r, that can be "decoded" with  streamAuto':*let myScanl f z = streamAuto' (accumD f z)scanl (+) 0 [1..10][0,3,6,10,15,21,28,36,45,55]myScanl (+) 0 [1..10][0,3,6,10,15,21,28,36,45]The only difference is that you don't get the last element. (You could force it out, if you wanted, by feeding any nonsense value in --- even t! --- and getting the result)*A "delayed" version of &, where the first output is the initial state of the accumulator, before applying the folding function. Useful in recursive bindings.+,The non-resuming/non-serializing version of ).,,The non-resuming/non-serializing version of *.-UA bunch of constant producers, mappers-of-output-streams, and forks-and-recombiners../Fork the input stream and divide the outputs. u maps u to the output stream; v$ will be a constant stream of that w, so you can write )s using numerical literals in code; see x instance./<Fork the input stream and add, multiply, etc. the outputs. y# will negate the ouptput stream. z$ will be a constant stream of that {, so you can write $s using numerical literals in code:streamAuto' (sumFrom 0) [1..10][1,3,6,10,15,21,28,36,45,55]#streamAuto' (4 + sumFrom 0) [1..10][5,7,10,14,19,25,32,40,49,59]0 String literals in code will be &s that constanty produce that string.@take 6 . streamAuto' (onFor 2 . "hello" --> "world") $ repeat ()1["hello","hello","world","world","world","world"]10Fork the input stream and mappend the outputs. | is a constant stream of |s, ignoring its input.RstreamAuto' (mconcat [arr (take 3), accum (++) ""]) ["hello","world","good","bye"]G["helhello","worhelloworld","goohelloworldgood","byehelloworldgoodbye"]2Fork the input stream and } the outputs. See the ~ instance.3*Finds the fixed point of self-referential 1s (for example, feeding the output stream of an J to itself). Mostly used with proc notation to allow recursive bindings.4Allows you to have an % only act on "some" inputs (only on b+s, for example), and be "paused" otherwise.!streamAuto' (sumFrom 0) [1,4,2,5] [1,5,7,12]UstreamAuto' (left (sumFrom 0)) [Left 1, Right 'a', Left 4, Left 2, Right 'b', Left 5]7[Left 1, Right 'a', Left 5, Left 6, Right 'b', Left 12]8Again mostly useful for "proc" notation, with branching.5 Gives us n, which is a "stateless" d that behaves just like a function; its outputs are the function applied the corresponding inputs. streamAuto' (arr negate) [1..10] [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]Also allows you to have an ` run on only the "first" or "second" field in an input stream that is tuples...and also allows Vs to run side-by-side on an input stream of tuples (run each on either tuple field).!streamAuto' (sumFrom 0) [4,6,8,7] [4,10,18,25]GstreamAuto' (first (sumFrom 0)) [(4,True),(6,False),(8,False),(7,True)]*[(4,True),(10,False),(18,False),(25,True)]%streamAuto' (productFrom 1) [1,3,5,2] [1,3,15,30]CstreamAuto' (sumFrom 0 *** productFrom 1) [(4,1),(6,3),(8,5),(7,2)][(4,1),(10,3),(18,15),(25,30)]@Most importantly, however, allows for "proc" notation; see the  ?https://github.com/mstksg/auto/blob/master/tutorial/tutorial.mdtutorial! for more details.6See  instance7See  instance8See ` instance.9 lets you map over the input stream, and  lets you map over the output! stream. Note that, as with all s,  is j.:#Gives the ability to "compose" two s; feeds the input stream into the first, feeds that output stream into the second, and returns as a result the output stream of the second.;When the underlying 'Monad'/'Applicative' m is an S, fork the input through each one and "squish" their results together inside the  context. See runTraversableA for similar use cases./streamAuto (arrM (mfilter even . Just)) [1..10]Nothing)streamAuto (arrM (Just . negate)) [1..10]%Just [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]IstreamAuto (arrM (mfilter even . Just)) <|> arrM (Just . negate)) [1..10] Just [-1,2,-3,4,-5,6,-7,8,-9,10]< creates the "constant" :streamAuto' (pure "foo") [1..5]["foo","foo","foo","foo","foo"] and ? etc. give you the ability to fork the input stream over many s, and recombine the results:streamAuto' (sumFrom 0) [1..10][ 1, 3, 6, 10, 15]#streamAuto' (productFrom 1) [1..10][ 1, 2, 6, 24, 120];streamAuto' (liftA2 (+) (sumFrom 0) (productFrom 1)) [1..5][ 2, 5, 12, 34, 135]For effectful , you can imagine gX as "forking" the input stream through both, and only keeping the result of the second: effect  *> sumFrom 0 %would, for example, behave just like sumFrom 0 , except printing the input to  at every step.=#Maps over the output stream of the .streamAuto' (sumFrom 0) [1..10][1,3,6,10,15,21,28,36,45,55](streamAuto' (show <$> sumFrom 0) [1..10]0["1","3","6","10","15","21","28","36","45","55"]F/monad morphism; the natural transformation the  to step the inputthe output, and the updated .the  to step the inputthe output, and the updated  to runinputoutput to runinputoutput to runinputupdated  to runinputupdated intercepting functionresuming/loading csaving d step functionresuming/loading csaving d(monadic) step function step function(monadic) step functionconstant value to be outputted+monadic action to be executed at every step pure function"monadic" functionstate transformer intial state (monadic) state transformer initial state!c2; strategy for reading and deserializing the stated&; strategy for serializing given statestate transformer intial state"c2; strategy for reading and deserializing the stated&; strategy for serializing given state(monadic) state transformer initial state#state transformer initial state$(monadic) state transformer initial state%accumulating functioninitial accumulator&(monadic) accumulating functioninitial accumulator'accumulating functionintial accumulator((monadic) accumulating functioninitial accumulator)accumulating functioninitial accumulator*(monadic) accumulating functioninitial accumulator+accumulating functionintial accumulator,(monadic) accumulating functioninitial accumulator-./0123456789:;<=,  !"#$%&'()*+,,  # $!"%'&()+*,@  !"#$%&'()*+,-./0123456789:;<=CExposing internal unsafe functions for working with >.(c) Justin Le 2015MIT justin@jle.imunstableportableNone025>5When used in the context of an input or output of an Auto, a > af represents a stream that occasionally, at "independent" or "discrete" points, emits a value of type a.Contrast this to Intervalo, where things are meant to be "on" or "off" for contiguous chunks at a time; blip streams are "blippy", and Intervals are "chunky".It's here mainly because it's a pretty useful abstraction in the context of the many combinators found in various modules of this library. If you think of an Auto m a (> b) as producing a "blip stream", then there are various combinators and functions that are specifically designed to manipulate blip streams.*For the purposes of the semantics of what >W is supposed to represent, its constructors are hidden. (Almost) all of the various >" combinators (and its very useful _ instance) "preserve >ness" --- one-at-a-time occurrences remain one-at-a-time under all of these combinators, and you should have enough so that direct access to the constructor is not needed.oIf you are creating a framework, library, or backend, you might want to manually create blip stream-producing Autos for your users to access. In this case, you can import the constructors and useful internal (and, of course, semantically unsafe) functions from Control.Auto.Blip.Internal.A7Merge two blip streams together; the result emits with either of the two merged streams emit. When both emit at the same time, emit the result of applying the given function on the two emitted values.:Note that this might be too strict for some purposes; see C and D for lazier alternatives.BSlightly more powerful AA, but I can't imagine a situation where this power is necessary.If only the first stream emits, emit with the first function applied to the value. If only the second stream emits, emit with the second function applied to the value. If both emit, then emit with the third function applied to both emitted values.C8Merges two blip streams together into one, which emits eithere of the original blip streams emit. If both emit at the same time, the left (first) one is favored.:Lazy on the second stream if the first stream is emitting.!If we discount laziness, this is A .D8Merges two blip streams together into one, which emits eitherg of the original blip streams emit. If both emit at the same time, the right (second) one is favored.:Lazy on the first stream if the second stream is emitting.!If we discount laziness, this is A ( ).EDeconstruct a ># by giving a default result if the >B is non-occuring and a function to apply on the contents, if the > is occuring.Try not to use if possible, unless you are a framework developer. If you're just making an application, try to use the other various combinators in this library. It'll help you preserve the semantics of what it means to be >py. Analogous to  from Prelude.H7Merge two blip streams together; the result emits with eitherX of the two merged streams emit. When both emit at the same time, emit the result of }-ing the values together.I7Merge two blip streams together; the result emits with eitherX of the two merged streams emit. When both emit at the same time, emit the result of }-ing the values together. >?@Amerging function first stream second stream merged streamBfunction for first streamfunction for second streammerging function first stream second stream merged streamCfirst stream (higher priority) second streamD first streamsecond stream (higher priority)E default valuefunction to apply on value> to deconstructFGHI>@?ABCDE>?@ABCDE >?@ABCDEFGHIC5D5HTools for working with "interval" semantics: "On or off" s.(c) Justin Le 2015MIT justin@jle.imunstableportableNoneMN, specialized with Identity as its underlying [. Analogous to  for .NhRepresents a relationship between an input and an output, where the output can be "on" or "off" (using  and !) for contiguous chunks of time."Just" a type alias for  m a ( b)?. If you ended up here with a link...no worries! If you see N m a b, just think  m a ( b)+ for type inference/type checking purposes.If you see something of type N, you can rest assured that it has "interval semantics" --- it is on and off for meaningfully contiguous chunks of time, instead of just on and off willy nilly. If you have a function that expects an N@, then the function expects its argument to behave in this way.O:The output stream is alwayas off, regardless of the input.+Note that any monadic effects of the input  when composed with OB are still executed, even though their result value is suppressed.off == pure NothingPSThe output stream is always on, with exactly the value of the corresponding input.toOn == arr JustQAn "interval collapsing" . A stream of on/off values comes in; the output is the value of the input when the input is on, and the "default value" when the input is off. Much like  from  Data.Maybe."fromInterval d = arr (fromMaybe d)RAn "interval collapsing" . A stream of on/off values comes in; when the input is off, the output is the "default value". When the input is off, the output is the given function applied to the "on" value. Much like  from  Data.Maybe.&fromIntervalWith d f = arr (maybe d f)SFor S n , the first n items in the output stream are always "on" (passing through with exactly the value of the corresponding input); for the rest, the output stream is always "off", suppressing all input values forevermore.-If a number less than 0 is passed, 0 is used.TFor T n , the first n items in the output stream are always "off", suppressing all input; for the rest, the output stream is always "on", outputting exactly the value of the corresponding input.UA combination of S and T; for U b e,, the output stream will be "on" from item b to item e inclusive with the value of the corresponding input; for all other times, the output stream is always off, suppressing any input.VThe output is "on" with exactly the value of he corresponding input when the input passes the predicate, and is "off" otherwise.&let a = whenI (\x -> x >= 2 && x <= 4)streamAuto' a [1..6]3[Nothing, Just 2, Just 3, Just 4, Nothing, Nothing]5Careful when using this; you could exactly create an N that "breaks" "interval semantics"; for example, 'whenI even', when you know your input stream does not consist of chunks of even numbers and odd numbers at a time.WLike V|, but only allows values to pass whenever the input does not satisfy the predicate. Blocks whenever the predicate is true.&let a = unlessI (\x -> x < 2 || x > 4)steamAuto' a [1..6]3[Nothing, Just 2, Just 3, Just 4, Nothing, Nothing]XTakes two input streams --- a stream of normal values, and a blip stream. Before the first emitted value of the input blip stream, the output is always "off", suppressing all inputs. After the first emitted value of the input blip stream, the output is always "on" with the corresponding value of the first input stream.!let a = after . (count &&& inB 3)"take 6 . streamAuto' a $ repeat ()2[Nothing, Nothing, Just 2, Just 3, Just 4, Just 5](count is the O that ignores its input and outputs the current step count at every step, and inB 3 is the 9 generating a blip stream that emits at the third step.)2Be careful to remember that in the above example, countE is still "run" at every step, and is progressed (and if it were an q with monadic effects, they would still be executed). It just isn't allowed to pass its output values through X until the blip stream emits.YTakes two input streams --- a stream of normal values, and a blip stream. Before the first emitted value of the input blip stream, the output is always "on" with the corresponding value of the first input stream. Afterl the first emitted value of the input blip stream, the output will be "off" forever, suppressing all input."let a = before . (count &&& inB 3)"take 5 . streamAuto' a $ repeat ()+[Just 0, Just 1, Nothing, Nothing, Nothing](count is the O that ignores its input and outputs the current step count at every step, and inB 3 is the 9 generating a blip stream that emits at the third step.)2Be careful to remember that in the above example, countE is still "run" at every step, and is progressed (and if it were an q with monadic effects, they would still be executed). It just isn't allowed to pass its output values through Y after the blip stream emits.ZTakes three input streams: a stream of normal values, a blip stream of "turning-on" blips, and a blip stream of "turning-off" blips. After the first blip stream emits, the output will switch to "on" with the value of the first input stream. After the second blip stream emits, the output will switch to "off", supressing all inputs. An emission from the first stream toggles this "on"; an emission from the second stream toggles this "off"./let a = between . (count &&& (inB 3 &&& inB 5))"take 7 . streamAuto' a $ repeat ()=[Nothing, Nothing, Just 2, Just 3, Nothing, Nothing, Nothing][The output is constantly "on" with the last emitted value of the input blip stream. However, before the first emitted value, it is "off". value of the input blip stream. From then on, the output is always the last emitted valuelet a = hold . inB 3streamAuto' a [1..5]*[Nothing, Nothing, Just 3, Just 3, Just 3]If you want an  m (> a) a (no E...just a "default value" before everything else), then you can use holdWith from Control.Auto.Blip...or also just [ with b or Q.\,The non-serializing/non-resuming version of [.]For ] n`, The output is only "on" if there was an emitted value from the input blip stream in the last n steps. Otherwise, is off.Like [L, but it only "holds" the last emitted value for the given number of steps.let a = holdFor 2 . inB 3streamAuto' a [1..7]=[Nothing, Nothing, Just 3, Just 3, Nothing, Nothing, Nothing]^,The non-serializing/non-resuming version of ]._ Stretches the last "on"/1 input over the entire range of following "off"/ inputs. Holds on to the last  until another one comes along.IstreamAuto' holdJusts [Nothing, Just 1, Just 3, Nothing, Nothing, Just 5]1[Nothing, Just 1, Just 3, Just 3, Just 3, Just 5]`,The non-resuming/non-serializing version of _.a,Forks a common input stream between the two Ns and returns, itself, an N. If the output of the first one is "on", the whole thing is on with that output. Otherwise, the output is exactly that of the second one.>let a = (onFor 2 . pure "hello") <|?> (onFor 4 . pure "world")"take 5 . streamAuto' a $ repeat ()A[Just "hello", Just "hello", Just "world", Just "world", Nothing][You can drop the parentheses, because of precedence; the above could have been written as:;let a' = onFor 2 . pure "hello" <|?> onFor 4 . pure "world"BWarning: If your underlying monad produces effects, remember that both gs are run at every step, along with any monadic effects, regardless of whether they are "on" or "off".Note that more often than not, b{ is probably more useful. This is useful only in the case that you really, really want an interval at the end of it all.b'Forks a common input stream between an N and an ., and returns, itself, a normal non-interval .. If the output of the first one is "on", the output of the whole thing is that "on" value. Otherwise, the output is exactly that of the second one.3let a1 = (onFor 2 . pure "hello") <|!> pure "world"#take 5 . streamAuto' a1 $ repeat ()-["hello", "hello", "world", "world", "world"]OThis one is neat because it associates from the right, so it can be "chained":let a2 = onFor 2 . pure "hello"# <|!> onFor 4 . pure "world" <|!> pure "goodbye!"#take 6 . streamAuto' a2 $ repeat ()<["hello", "hello", "world", "world", "goodbye!", "goodbye!"]  a <|!> b <|!> c associates as  a <|!> (b <|!> c)So using this, you can "chain" a bunch of choices between intervals, and then at the right-most, "final" one, provide the default behavior.BWarning: If your underlying monad produces effects, remember that both gs are run at every step, along with any monadic effects, regardless of whether they are "on" or "off".c"Forks an input stream between all N"s in the list. The result is an N0 whose output is "on" when any of the original Ns is on, with the value of the first "on" one."chooseInterval == foldr (<|?>) offd"Forks an input stream between all N s in the list, plus a "default .. The output is the value of the first "on" N3; if there isn't any, the output from the "default  " is used.choose == foldr (<|!>)eLifts an  m a b (transforming as into b s) into an  m ( a) ( b) (or, N m ( a) b, transforming  intervals of as into  intervals of b.It does this by running the 3 as normal when the input is "on", and freezing itbeing "off" when the input is off/..let a1 = during (sumFrom 0) . onFor 2 . pure 1#take 5 . streamAuto' a1 $ repeat ()+[Just 1, Just 2, Nothing, Nothing, Nothing]/let a2 = during (sumFrom 0) . offFor 2 . pure 1#take 5 . streamAuto' a2 $ repeat ()*[Nothing, Nothing, Just 1, Just 2, Just 3](Remember that  x is the 7 that ignores its input and constantly just pumps out x at every step)(Note the difference between putting the sumFrom "after" the T in the chain with e. (like the previous example) and putting the sumFrom "before":&let a3 = offFor 2 . sumFrom 0 . pure 1#take 5 . streamAuto' a3 $ repeat ()*[Nothing, Nothing, Just 3, Just 4, Just 5]In the first case (with a2), the output of  1 was suppressed by T, and e (sumFrom 0)v was only summing on the times that the 1's were "allowed through"...so it only "starts counting" on the third step.In the second case (with a3), the output of the  12 is never suppressed, and went straight into the sumFrom 0. sumFrom@ is always summing, the entire time. The final output of that sumFrom 0 is suppressed at the end with T 2.fLifts (more technically, "binds") an N m a b into an N m ( a) b.Does this by running the 3 as normal when the input is "on", and freezing itbeing "off" when the input is off/.It's kind of like e, but the resulting  ( b)) is "joined" back into a  b.bindI a == fmap join (during a)-This is really an alternative formulation of g ; typically, you will be using gW more often, but this form can also be useful (and slightly more general). Note that:bindI f == compI f idWThis combinator allows you to properly "chain" ("bind") together series of inhibiting s. If you have an N m a b and an N m b c, you can chain them into an N m a c. f :: N m a b g :: N m b c f g . f :: N m a c (Users of libraries with built-in inhibition semantics like Yampa and netwire might recognize this as the "default" composition in those other libraries)See g for examples of this use case.g Composes two Ns, the same way that  composes two s: x(.) :: Auto m b c -> Auto m a b -> Auto m a c compI :: Interval m b c -> Interval m a b -> Interval m a c Basically, if any N_ in the chain is "off", then the entire rest of the chain is "skipped", short-circuiting a la .(Users of libraries with built-in inhibition semantics like Yampa and netwire might recognize this as the "default" composition in those other libraries)%As a contrived example, how about an ^ that only allows values through during a window...between, say, the second and fourth steps:<let window' start dur = onFor dur `compI` offFor (start - 1)streamAuto' (window' 2 3)3[Nothing, Just 2, Just 3, Just 4, Nothing, Nothing]MNOPQ!value to output for "off" periodsR default value, when input is off"function to apply when input is onS amount of steps to stay "on" forTamount of steps to be "off" forUstart of windowend of window (inclusive)Vinterval predicateWinterval predicateXYZ[\]2number of steps to hold the last emitted value for^2number of steps to hold the last emitted value for_`achoice 1choice 2b interval  "normal" cthe s to run and choose fromdthe % to behave like if all others are s to run and choose frome to lift to work over intervalsfN to bindg compose this N......to this oneMNOPQRSTUVWXYZ[\]^_`abcdefgNMOPQRSTUVWbacdXYZ[\]^_`egfMNOPQRSTUVWXYZ[\]^_`abcdefga3b3g18s that act as generators or "producers", ignoring input.(c) Justin Le 2015MIT justin@jle.imunstableportableNoneThAn N that ignores the input stream and just outputs items from the given list. Is "on" as long as there are still items in the list left, and "off" after there is nothing left in the list to output.Serializes itself by storing the entire rest of the list in binary, so if your list is long, it might take up a lot of space upon storage. If your list is infinite, it makes an infinite binary, so be careful!i[ can be used for longer lists or infinite lists; or, if your list can be boild down to an unfoldr, you can use k.8Storing: O(n) time and space on length of remaining list.Loading: O(1) time in the number of times the E has been stepped + O(n) time in the length of the remaining list.i A version of hQ that is safe for long or infinite lists, or lists with unserializable elements.@There is a small cost in the time of loading/resuming, which is O(n)o on the number of times the Auto had been stepped at the time of saving. This is because it has to drop the nA first elements in the list, to "resume" to the proper position.@Storing: O(1) time and space on the length of the remaining list.Loading: O(n) time on the number of times the P has been stepped, maxing out at O(n) on the length of the entire input list.j,The non-resuming/non-serializing version of h.k Analogous to unfoldr from Prelude. Creates an NK (that ignores its input) by maintaining an internal accumulator of type c_ and, at every step, applying to the unfolding function to the accumulator. If the result is  , then the N" will turn "off" forever (output  forever); if the result is  (y, acc), then it will output y and store acc as the new accumulator.Given an initial accumulator.6let countFromTil n m = flip unfold n $ \i -> if i <= mE then Just (i, i+1)? else Nothing4take 8 . streamAuto' (countFromTil 5 10) $ repeat ()C[Just 5, Just 6, Just 7, Just 8, Just 9, Just 10, Nothing, Nothing]k f c0 behaves like overList (unfoldr f c0).lLike k(, but the unfolding function is monadic.m.The non-resuming & non-serializing version of k.n.The non-resuming & non-serializing version of l.o Analogous to  from Preludez. Keeps accumulator value and continually applies the function to the accumulator at every step, outputting the result.2The first result is the initial accumulator value.3take 10 . streamAuto' (iterator (*2) 1) $ repeat ()'[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]pLike o, but with a monadic function.q,The non-resuming/non-serializing version of o.r,The non-resuming/non-serializing version of p.s5Continually enumerate from the starting value, using .t,The non-serializing/non-resuming version of s.uhGiven a function from discrete enumerable inputs, iterates through all of the results of that function.4take 10 . streamAuto' (discreteF (^2) 0) $ repeat ()$[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]v,The non-resuming/non-serializing version of u.wnTo get every output, executes the monadic action and returns the result as the output. Always ignores input.&This is basically like an "effectful" :  :: b ->  m a b w :: m b ->  m a b The output of ' is always the same, and the output of wM is always the result of the same monadic action. Both ignore their inputs.Fun times when the underling [ is, for instance, Reader.,let a = effect ask :: Auto (Reader b) a b#let r = evalAuto a () :: Reader b brunReader r "hello""hello"runReader r 100100%If your underling monad has effects (, State, , Writer4, etc.), then it might be fun to take advantage of g from Control.Applicative$ to "tack on" an effect to a normal :Elet a = effect (modify (+1)) *> sumFrom 0 :: Auto (State Int) Int Intlet st = streamAuto a [1..10]let (ys, s') = runState st 0ys[1,3,6,10,15,21,28,36,45,55]s'10Our  a behaves exactly like sumFrom 0V, except at each step, it also increments the underlying/global state by one. It is sumFrom 0 with an "attached effect".h!list to output element-by-elementi!list to output element-by-elementj!list to output element-by-elementkunfolding functioninitial accumulatorlunfolding functioninitial accumulatormunfolding functioninitial accumulatornunfolding functioninitial accumulatoroiterating function!starting value and initial outputp(monadic) iterating function!starting value and initial outputqiterating function!starting value and initial outputr(monadic) iterating function!starting value and initial outputs initial valuet initial valueudiscrete function initial inputvdiscrete function initial inputw$monadic action to contually execute.hijklmnopqrstuvwhjiwoqpruvkmlnsthijklmnopqrstuvw 2s useful for various commonly occurring processes.(c) Justin Le 2015MIT justin@jle.imunstableportableNonexjThe stream of outputs is the cumulative/running sum of the inputs so far, starting with an initial count.:The first output takes into account the first input. See zC for a version where the first output is the initial count itself.sumFrom x0 = accum (+) x0y,The non-resuming/non-serializing version of x.zLike x0, except the first output is the starting count.let a = sumFromD 5let (y1, a') = stepAuto' a 10y15let (y2, _ ) = stepAuto' a' 3y210streamAuto' (sumFrom 0) [1..10][1,3,6,10,15,21,28,36,45,55] streamAuto' (sumFromD 0) [1..10][0,1,3,6,10,15,21,28,36,45]It's x, but "delayed".Useful for recursive bindings, where you need at least one value to be able to produce its "first output" without depending on anything else."sumFromD x0 = sumFrom x0 . delay 0#sumFromD x0 = delay x0 . sumFrom x0{,The non-resuming/non-serializing version of z.|lThe output is the running/cumulative product of all of the inputs so far, starting from an initial product.productFrom x0 = accum (*) x0},The non-resuming/non-serializing version of |.~VThe output is the the difference between the input and the previously received input.First result is a , so you can use b or Q or  fromMaybe to get a "default first value".streamAuto' deltas [1,6,3,5,8],[Nothing, Just 5, Just (-3), Just 2, Just 3] Usage with b:let a = deltas <|!> pure 100.streamAuto' (deltas <|!> pure 100) [1,6,3,5,8][100, 5, -3, 2, 3] Usage with  fromMaybe:2streamAuto' (fromMaybe 100 <$> deltas) [1,6,3,5,8][100, 5, -3, 2, 3],The non-resuming/non-serializing version of ~.%The output is the running/cumulative 1 of all of the input seen so far, starting with |.Dstreamauto' mappender . map Last $ [Just 4, Nothing, Just 2, Just 3]<[Last (Just 4), Last (Just 4), Last (Just 2), Last (Just 3)]4streamAuto' mappender ["hello","world","good","bye"];["hello","helloworld","helloworldgood","helloworldgoodbye"] mappender = accum mappend mempty,The non-resuming/non-serializing version of .The output is the running }-sum ( for \) of all of the input values so far, starting with a given starting value. Basically like , but with a starting value.BstreamAuto' (mappendFrom (Max 0)) [Max 4, Max (-2), Max 3, Max 10][Max 4, Max 4, Max 4, Max 10]mappendFrom m0 = accum (<>) m0,The non-resuming/non-serializing version of .TThe output is the sum of the past inputs, multiplied by a moving window of weights.-For example, if the last received inputs are  [1,2,3,4]= (from most recent to oldest), and the window of weights is  [2,0.5,4], then the output will be 1*2 + 0.5*2 + 4*3, or 15J. (The weights are assumed to be zero past the end of the weight window)CThe immediately received input is counted as a part of the history.Mathematically, 9y_n = w_0 * x_(n-0) + w_1 + x_(n-1) + w_2 * x_(n-1) + ... , for all w0s in the weight window, where the first item is w_0. y_n is the nth output, and x_n is the n th input.Note that this serializes the history of the input...or at least the history as far back as the entire window of weights. (A weight list of five items will serialize the past five received items) If your weight window is very long (or infinite), then serializing is a bad idea!The second parameter is a list of a "starting history", or initial conditions, to be used when the actual input history isn't long enough. If you want all your initial conditions/starting history to be 0, just pass in [].'Minus serialization, you can implement x as: )sumFrom n = movingAverage (repeat 1) [n] #And you can implement a version of ~ as: !deltas = movingAverage [1,-1] [] kIt behaves the same, except the first step outputs the initially received value. So it's realy a bit like %(movingAverage [1,-1] []) == (deltas  |! id) HWhere for the first step, the actual input is used instead of the delta.&Name comes from the statistical model.,The non-serializing/non-resuming version of .sAny linear time independent stream transformation can be encoded by the response of the transformation when given  [1,0,0,0...], or 1 :  0. So, given an LTI , if you feed it 1 :  0>, the output is what is called an "impulse response function".For any LTI 3, we can reconstruct the behavior of the original # given its impulse response. Give E an impulse response, and it will recreate/reconstruct the original .7let getImpulseResponse a = streamAuto' a (1 : repeat 0);let sumFromImpulseResponse = getImpulseResponse (sumFrom 0)streamAuto' (sumFrom 0) [1..10][1,3,6,10,15,21,28,36,45,55]<streamAuto' (impulseResponse sumFromImpulseResponse) [1..10][1,3,6,10,15,21,28,36,45,55]NUse this function to create an LTI system when you know its impulse response.Gtake 10 . streamAuto' (impulseResponse (map (2**) [0,-1..])) $ repeat 1M[1.0,1.5,1.75,1.875,1.9375,1.96875,1.984375,1.9921875,1.99609375,1.998046875]LAll impulse response after the end of the given list is assumed to be zero.Mathematically, 9y_n = h_0 * x_(n-0) + h_1 + x_(n-1) + h_2 * x_(n-1) + ... , for all h_n0 in the input response, where the first item is h_0.Note that when this is serialized, it must serialize a number of input elements equal to the length of the impulse response list...so if you give an infinite impulse response, you might want to use , or not serialize. By the way,  ir ==  ir [].,The non-serializing/non-resuming version of .iThe output is the sum of the past outputs, multiplied by a moving window of weights. Ignores all input.%For example, if the last outputs are  [1,2,3,4]= (from most recent to oldest), and the window of weights is  [2,0.5,4], then the output will be 1*2 + 0.5*2 + 4*3, or 15J. (The weights are assumed to be zero past the end of the weight window)Mathematically, )y_n = w_1 * y_(n-1) + w_2 * y_(n-2) + ... , for all w0 in the weight window, where the first item is w_1.Note that this serializes the history of the outputs...or at least the history as far back as the entire window of weights. (A weight list of five items will serialize the past five outputted items) If your weight window is very long (or infinite), then serializing is a bad idea!The second parameter is a list of a "starting history", or initial conditions, to be used when the actual output history isn't long enough. If you want all your initial conditions/starting history to be 0, just pass in [].^You can use this to implement any linear recurrence relationship, like he fibonacci sequence:-evalAutoN' 10 (autoRegression [1,1] [1,1]) ()[2,3,5,8,13,21,34,55,89,144]@evalAutoN' 10 (fromList [1,1] --> autoRegression [1,1] [1,1]) ()[1,1,2,3,5,8,13,21,34,55]KWhich is 1 times the previous value, plus one times the value before that.TYou can create a series that doubles by having it be just twice the previous value:)evalAutoN' 10 (autoRegression [2] [1]) ()"[2,,4,8,16,32,64,128,256,512,1024]&Name comes from the statistical model.,The non-serializing/non-resuming version of .A combination of  and &. Inspired by the statistical model.Mathematically: zy_n = wm_0 * x_(n-0) + wm_1 * x_(n-1) + wm_2 * x_(n-2) + ... + wa_1 * y_(n-1) + wa_2 * y_(n-1) + ... Where wm_nFs are all of the "moving average" weights, where the first weight is wm_0, and wa_nFs are all of the "autoregression" weights, where the first weight is wa_1.,The non-serializing/non-resuming version of .x initial county initial countz initial count{ initial count|initial product}initial product~ initial value initial value:weights to apply to previous inputs, from most recent#starting history/initial conditions:weights to apply to previous inputs, from most recent#starting history/initial conditionsthe impulse response functionthe impulse response function;weights to apply to previous outputs, from most recent#starting history/initial conditions;weights to apply to previous outputs, from most recent#starting history/initial conditions,weights for the "auto-regression" components+weights for the "moving average" components.an "initial history" of outputs, recents first-an "initial history" of inputs, recents first,weights for the "auto-regression" components+weights for the "moving average" components.an "initial history" of outputs, recents first-an "initial history" of inputs, recents firstxyz{|}~xyz{|}~xyz{|}~ ,Various utilities for running and unrolling ;s, both interactively and non-interactively.(c) Justin Le 2015MIT justin@jle.imunstableportableNoneOT Streams the / over a list of inputs; that is, "unwraps" the  [a] -> m [b] inside. Streaming is done in the context of the underlying monad; when done consuming the list, the result is the list of outputs updated/next ( in the context of the underlying monad.Basically just steps the ] by feeding in every item in the list and pops out the list of results and the updated/next &, monadically chaining the steppings.See A for a simpler example; the following example uses effects from ( to demonstrate the monadic features of .2let a = arrM print *> sumFrom 0 :: Auto IO Int Int(ys, a') <- overList a [1..5]1 -- IO effects2345ys [1,3,6,10,15] (ys', _) <- overList a' [11..15]11 -- IO effects12131415ys'[26,38,51,65,80]a is like sumFrom 0w, except at every step, prints the input item to stdout as a side-effect. Note that in executing we get the updated a'A, which ends up with an accumulator of 15. Now, when we stream a'7, we pick up were we left off (from 15) on the results.Like , but "streams" the  over all elements of any , returning the final updated . Streams an / over a list of inputs; that is, "unwraps" the  [a] -> [b]R inside. When done comsuming the list, returns the outputs and the updated/next .6let (ys, updatedSummer) = overList' (sumFrom 0) [1..5]ys[1, 3, 6, 10, 15]/let (ys', _) = streamAuto' updatedSummer [1..5]ys'[16, 18, 21, 25, 30]MIf you wanted to stream over an infinite list then you don't care about the  at the end, and probably want .Like , but "streams" the  over all elements of any  Traversable', returning the final updated . Stream an  over a list, returning the list of results. Does this "lazily" (over the Monad), so with most Monads, this should work fine with infinite lists. (That is,  (arrM f) behaves exactly like m f, and you can reason with s as if you'd reason with mapM on an infinite list)'Note that, conceptually, this turns an  m a b into an  [a] -> m [b].See I for a simpler example; here is one taking advantage of monadic effects:2let a = arrM print *> sumFrom 0 :: Auto IO Int Intys <- streamAuto a [1..5]1 -- IO effects2345ys[1,3,6,10,15] -- the resulta here is like sumFrom 0J, except at every step, prints the input item to stdout as a side-effect.LNote that we use "stream" here slightly differently than in libraries like pipes or conduit. We don't stream over the m Monad (like IO)...we stream over the input elements . Using | on an infinite list allows you to "stop", for example, to find the result...but it will still sequence all the *effects*. For example:/take 10 <$> streamAuto (arrM print *> id) [1..] Will execute 2 on every element before "returning" with [1..10].Jflip runState 0 $ take 10 <$> streamAuto (arrM (modify . (+)) *> id) [1..]0([1,2,3,4,5,6,7,8,9,10], .... (never terminates)This will immediately return the "result", and you can bind to the result with `(>>=)`, but it'll never return a "final state", because the final state involves executing all of the s.In other words, we stream values, not effectsR. You would analyze this behavior the same way you would look at something like m.+If you want to stream effects, you can use  or ,, and use an effects streaming library like pipes (or anything with ListT)...this will give the proper streaming of effects with resource handling, handling infinite streams in finite space with finite effects, etc. Stream an  over a list, returning the list of results. Does this lazily, so this should work fine with (and is actually somewhat designed for) infinite lists.%Note that conceptually this turns an  a b into an  [a] -> [b]streamAuto' (arr (+3)) [1..10][4,5,6,7,8,9,10,11,12,13]streamAuto' (sumFrom 0) [1..5] [1,3,6,10,15]>streamAuto' (productFrom 1) . streamAuto' (sumFrom 0) $ [1..5][1,3,18,180,2700]0streamAuto' (productFrom 1 . sumFrom 0) $ [1..5][1,3,18,180,2700]streamAuto' id [1..5] [1,2,3,4,5];Streams (in the context of the underlying monad) the given  with a stream of constant values as input, a given number of times. After the given number of inputs, returns the list of results and the next/updated ), in the context of the underlying monad..stepAutoN n a0 x = overList a0 (replicate n x)See I for a simpler example; here is one taking advantage of monadic effects:2let a = arrM print *> sumFrom 0 :: Auto IO Int Int(ys, a') <- stepAutoN 5 a 33 -- IO effects3333ys[3,6,9,12,15] -- the result(ys'', _) <- stepAutoN 5 a' 55 -- IO effects5555ys''[20,25,30,35,50] -- the resulta here is like sumFrom 0J, except at every step, prints the input item to stdout as a side-effect.Streams the given  with a stream of constant values as input, a given number of times. After the given number of inputs, returns the list of results and the next/updated .0stepAutoN' n a0 x = overList' a0 (replicate n x))let (ys, a') = stepAutoN' 5 (sumFrom 0) 3ys [3,6,9,12,15] let (ys', _) = stepAutoN' 5 a' 5ys'[20,25,30,35,40];Streams (in the context of the underlying monad) the given  with a stream of constant values as input, a given number of times. After the given number of inputs, returns the list of results in the context of the underlying monad.Like , but drops the "next &". Only returns the list of results.2let a = arrM print *> sumFrom 0 :: Auto IO Int Intys <- evalAutoN 5 a 33 -- IO effects3333ys[3,6,9,12,15] -- the resulta here is like sumFrom 0J, except at every step, prints the input item to stdout as a side-effect.Streams the given  with a stream of constant values as input, a given number of times. After the given number of inputs, returns the list of results and the next/updated .Like , but drops the "next &". Only returns the list of results.evalAutoN' 5 (sumFrom 0) 3 [3,6,9,12,15] Lifts an  m a b to one that runs "through" a ,  m (t a) (t b)L. It does this by running itself sequentially over every element "in" the  at every input.[This can be thought of as a polymorphic version of many other combinators in this library: during = throughT :: Auto m a b -> Interval m (Maybe a) b perBlip = throughT :: Auto m a b -> Auto m (Blip a) (Blip b) accelOverList = throughT :: Auto m a b -> Auto m [a] [b] iThe specialized versions will still be more performant, but this will be more general...you can run the  through an input IntMap, for example.1Note that this is actually an endofunctor on the  Category. That is, for all s lifted and all lawful s, usage should obey the laws: <throughT id = id throughT g . throughT f = throughT (g . f) -Heavy duty abstraction for "self running" an }. Give a starting input action, a (possibly side-effecting) function from an output to the next input to feed in, and the y, and you get a feedback loop that constantly feeds back in the result of the function applied to the previous output. Stops) when the "next input" function returns .Note that the none of the results are actually returned from the loop. Instead, if you want to process the results, they must be utilized in the "side-effects' of the "next input" function. (ie, a write to a file, or an accumulation to a state).A generalized version of  where the [ you are "running" the  in is different than the [ underneath the 8. You just need to provide the natural transformation.Run an L "interactively". Every step grab a string from stdin, and feed it to the M . If the Mo is "off", ends the session; if it is "on", then prints the output value to stdout and repeat all over again.If your  outputs something other than a , you can use j to transform the output into a  en-route (like j ).If your ! takes in something other than a  , you can " a function to convert the input  to whatever intput your  expects. You can use  or  if you have an  or M that takes something Iable, to chug along until you find something non-readable; there's also % which handles most of that for you.Outputs the final M! when the interaction terminates.Like interact, but instead of taking M   , takes any M a b as long as a is  and b is .+Will "stop" if either (1) the input is not -able or (2) the M turns off.Outputs the final ! when the interaction terminates.Like interact1, but much more general. You can run it with an  of any underlying [?, as long as you provide the natural transformation from that [ to .The  can any  b=; you have to provide a function to "handle" it yourself; a b ->  G. You can print the result, or write the result to a file, etc.; the f parameter determines whether or not to "continue running", or to stop and return the final updated .Turn an  that takes a "readable" a and outputs a b into an  that takes a  and outputs a  b . When the  is successfuly readable as the a, it steps the  and outputs a succesful % result; when it isn't, it outputs a  on that step.*let a0 = duringRead (accum (+) (0 :: Int)) let (y1, a1) = stepAuto' a0 "12"y1Just 12$let (y2, a2) = stepAuto' a1 "orange"y2Nothinglet (y3, _ ) = stepAuto' a2 "4"y3Just 16See interact for neat use cases.Like , but the original  would output a  b instead of a b . Returns  if either the $ fails to parse or if the original  returned  ; returns  if the  parses and the original  returned .See interact for neat use cases.A generalized version of  that can run on any  mI; all that is required is a natural transformation from the underyling [ m to . Runs the  in IO with inputs read from a  queue, from Control.Concurrency.Chan. It'll block until the  has a new input, run the  with the received input, process the output with the given handling function, and start over if the handling function returns l. Turns an  Auto m' a b and an "input producer" m a? into a "ListT compatible effectful stream", as described at Qhttp://www.haskellforall.com/2014/11/how-to-build-library-agnostic-streaming.htmlAny library that offers a "ListTK" type can use this result...and usually turn it into an effectful stream.For example, the pipes library offers runListT. so you can run this, constantly pulling out as from the stream using the m an, feeding it in, and moving forward, all with the effect stream manipulation tools and resource handling of pipes.This is useful because autoH, the library, mainly provides tools for working with transformers for valuex streams, and not effect streams or streams of effects. Using this, you can potentially have the best of both worlds. Turns an  Auto m' a bU with a list of inputs into a "ListT compatible effectful stream", as described at Qhttp://www.haskellforall.com/2014/11/how-to-build-library-agnostic-streaming.htmlAny library that offers a "ListTK" type can use this result...and usually turn it into an effectful stream.For example, the pipes library offers runListT# so you can run this, running the ^ over the input list, all with the effect stream manipulation tools and resource handling of pipes.This is useful because autoH, the library, mainly provides tools for working with transformers for valuex streams, and not effect streams or streams of effects. Using this, you can potentially have the best of both worlds.the  to runlist of inputs to step the  with list of outputs and the updated the  to run of inputs to step the  with of outputs and the updated the  to runlist of inputs to step the  with list of outputs and the updated the  to run of inputs to step the  with of outputs and the updated  to stream input stream output stream to stream input stream output streamnumber of times to step the the  to runthe repeated input list of outputs and the updated number of times to step the the  to runthe repeated input list of outputs and the updated number of times to step the the  to runthe repeated inputlist of outputsnumber of times to step the the  to runthe repeated input list of outputs and the updated  to run "through" a !action to retrieve starting input"handling output and next input in mreturn the ran/updated  in mnatural transformation from m' (the Auto monad) to m (the running monad)!action to retrieve starting input"handling output and next input in m in monad m'!return the resulting/run Auto in mM to run interactivelyfinal M after it allM to run interactivelyfinal M after it all+natural transformation from the underlying [ of the  to $function to "handle" each succesful  output to run "interactively"final  after it all taking in a readable a , outputting b taking in  , outputting  b taking in a readable a , outputting  b taking in  , outputting  b/natural transformation from the underling [ of the  to )function to "handle" each succesful 8 output; result is whether or not to continue. queue to pull input from. to runfinal - after it all, when the handle resturns k)function to "handle" each succesful 8 output; result is whether or not to continue. queue to pull input from. to runfinal - after it all, when the handle resturns k-function to change the underyling monad from m' to maction to generate inputs"Auto to run as an effectful streamListT-compatible type-function to change the underyling monad from m' to minputs to stream on to streamListT"-like structure sequencing effectsSerializing and deserializing ,s to and from disk, and also + transformers focused around serialization.(c) Justin Le 2015MIT justin@jle.imunstableportableNoneTGive a  and an , and 0 will attempt to resume the saved state of the $ from disk, reading from the given . Will return b- upon a decoding error, with the error, and  if the decoding is succesful.Like , but will return the original 8 (instead of a resumed one) if the file does not exist.!Useful if you want to "resume an C" "if there is" a save state, or just use it as-is if there isn't.Like L, but will throw a runtime exception on a failure to decode or an IO error.Given a  and an ), serialize and freeze the state of the  as binary to that . Transforms the given  into an / that constantly saves its state to the given + at every "step". Requires an underlying .Note that (unless the  depends on IO), the resulting  is meant to be operationally  identical, in its inputs/outputs to the original one. Transforms the given  into an  that, when you first? try to run or step it, "loads" itself from disk at the given .KWill throw a runtime exception on either an I/O error or a decoding error.Note that (unless the  depends on IO), the resulting  is meant to be operationally  identical in its inputs/outputs to the fast-forwarded original .Like j, except silently suppresses all I/O and decoding errors; if there are errors, it returns back the given  as-is.yUseful for when you aren't sure the save state is on disk or not yet, and want to resume it only in the case that it is.A combination of  and  . When the 7 is first run, it loads the save state from the given ^ and fast forwards it. Then, subsequently, it updates the save state on disk on every step.Like 0, except suppresses all I/O and decoding errors.!Useful in the case that when the  is first run and there is no save state yet on disk (or the save state is corrupted), it'll "start a new one"; if there is one, it'll load it automatically. Then, on every further step in both cases, it'll update the save state. Takes an $ that produces a blip stream with a $ and a value, and turns it into an + that, outwardly, produces just the value._Whenever the output blip stream emits, it automatically serializes and saves the state of the  to the emitted .In practice, this allows any K to basically control when it wants to "save", by providing a blip stream.2The following is an alternative implementation of 7, except saving every two steps instead of every step: saving2 fp a =  (a &&& (every 2 .  fp)) Or, in proc notation: esaving2 fp a = saveFromB $ proc x -> do y <- a -< x b <- every 2 -< fp id -< (y, b) (Recall that every n is the Auto& that emits the received value every n steps)-In useful real-world cases, you can have the  decide whether or not to save itself based on its input. Like, for example, when it detects a certain user command, or when the user has reached a given location.The following takes a  and an  (a), and turns it into an  that "saves" whenever a) crosses over from positive to negative. _saveOnNegative fp a = saveFromB $ proc x -> do y <- a -< x saveNow <- became# (< 0) -< y id -< (y, fp  saveNow)  Contrast to `, where the saves are triggered by outside input. In this case, the saves are triggered by the  to be saved itself. Takes an  that outputs a b and a blip stream of s and returns an  that ouputs only that bT stream...but every time the blip stream emits, it "resets/loads" itself from that .(The following is a re-implementation of T...except delayed by one (the second step that is run is the first "resumed" step). loading2 fp a = ? $ proc x -> do y <- a -< x loadNow <-  immediately -< fp  -< (y, loadNow) ;(the blip stream emits only once, immediately, to re-load).&In the real world, you could have the ; decide to reset or resume itself based on a user command: loadFrom = loadFromB $ proc x -> do steps <- count -< () toLoad <- case words x of ("load":fp:_) -> do immediately -< fp _ -> do never -< () id -< (steps, toLoad) DThis will throw a runtime error on an IO exception or parsing error.Like x, except silently ignores errors. When a load is requested, but there is an IO or parse error, the loading is skipped. Takes an L and basically "wraps" it so that you can trigger saves with a blip stream.For example, we can take sumFrom 0:  (sumFrom 0) ::   (e, > ) e It'll behave just like sumFrom 0 (with the input you pass in the first field of the tuple)...and whenever the blip stream (the second field of the input tuple) emits, it'll save the state of sumFrom 0 to disk at the given . Contrast to  , where the J itself can trigger saves; in this one, saves are triggered "externally".)Might be useful in similar situations as 5, except if you want to trigger the save externally. Takes an ` and basically "wraps" it so that you can trigger loads/resumes from a file with a blip stream.For example, we can take sumFrom 0:  (sumFrom 0) ::   (e, > ) e It'll behave just like sumFrom 0 (with the input you pass in the first field of the tiple)...and whenever the blip stream (the second field of the input tuple) emits, it'll "reset" and "reload" the sumFrom 0 from the  on disk.HWill throw a runtime exception if there is an IO error or a parse error. Contrast to  , where the W itself can trigger reloads/resets; in this one, the loads are triggered "externally".)Might be useful in similar situations as 8, except if you want to trigger the loading externally.Like x, except silently ignores errors. When a load is requested, but there is an IO or parse error, the loading is skipped.filepath to read from to resumefilepath to read from to resumefilepath to read from to resumefilepath to write to to serializefilepath to write to to transformfilepath to read from to transformfilepath to read from# to transform (or return unchanged)"filepath to read from and write to to transform"filepath to read from and write to to transform producing a value b and a blip stream with a  to save toj with an output and a blip stream to trigger re-loading itself from the given filepathj with an output and a blip stream to trigger re-loading itself from the given filepath to make saveable-by-trigger to make reloadable-by-trigger to make reloadable-by-trigger    s and O transformers for observing and manipulating the flow of "time".(c) Justin Le 2015MIT justin@jle.imunstableportableNone$ A simple E that ignores all input; its output stream counts upwards from zero.'take 10 . streamAuto' count $ repeat ()[0,1,2,3,4,5,6,7,8,9]*A non-resuming/non-serializing version of .An X that returns the last value received by it. Given an "initial value" to output first.GFrom the signal processing world, this is known as the "lag operator" L.This is (potentially) a very dangerous , because its usage and its very existence opens the door to breaking denotative/declarative style and devolving into imperative style coding. However, when used where it is supposed to be used, it is more or less invaluable, and will be an essential part of many programs.Its main usage is for dealing with recursive bindings. If you ever are laying out recursive bindings in a high-level/denotative way, you need to have at least one value be able to have a "initial output" without depending on anything else.  and  allow you to do this.See the  Dhttps://github.com/mstksg/auto-examples/blob/master/src/Recursive.hs recursive; example for more information on the appropriate usage of  and .!streamAuto' (lastVal 100) [1..10][100,1,2,3,4,5,6,7,8,9],The non-resuming/non-serializing version of .Like n", but applies the function to the previous valueN of the input, instead of the current value. Used for the same purposes as : to manage recursive bindings.5Warning: Don't use this to do imperative programming!arrD id == lastVal%streamAuto' (arrD negate 100) [1..10] [100,-1,-2,-3,-4,-5,-6,-7,-8,-9],The non-resuming/non-serializing version of . An alias for p; used in contexts where "delay" is more a meaningful description than "last value". All of the warnings for > still apply, so you should probably read it if you haven't :),The non-resuming/non-serializing version of .Like , except has as many "initial values" as the input list. Outputs every item in the input list in order before returning the first received value.delayList [y0] = delay y0*streamAuto' (delayList [3,5,7,11]) [1..10][3,5,7,11,1,2,3,4,5,6],The non-resuming/non-serializing version of .Like P, except delays the desired number of steps with the same initial output value.(delayN n x0 = delayList (replicate n x0)delayN 1 x0 = delay x0 streamAuto' (delayN 3 0) [1..10][0,0,0,1,2,3,4,5,6,7],The non-resuming/non-serializing version of  "stretch" an  out, slowing time.  n a. will take one input, repeat the same output nS times (ignoring input), and then take another. It ignores all inputs in between.let a = stretch 2 (sumFrom 0)streamAuto' a [1,8,5,4,3,7,2,0] [1,1,6,6,9,9,11,11]%-- [1,_,5,_,3,_,2 ,_ ] <-- the inputs,The non-resuming/non-serializing version of .A more general version of ; instead of just ignoring and dropping the "stretched/skipped intervals", accumulate all of them up with the given accumulating function and then "step" them all at once on every nth tick. Also, stead of returning exactly the same output every time over the stretched interval, output a function of the original output during the stretched intervals.streamAuto' (sumFrom 0) [1..10]%[1, 3, 6, 10, 15, 21, 28, 36, 45 ,55]=streamAuto' (stretchAccumBy (+) negate 4 (sumFrom 0)) [1..10]%[1,-1,-1, -1, 15,-15,-15,-15, 45,-45][Here, instead of feeding in a number every step, it "accumulates" all of the inputs using  and "blasts them into" sumFrom 0P every 4 steps. In between the blasts, it outputs the negated last seen result. You can recover the behavior of  with  (flip const) id.+The non-serialized/non-resuming version of .Like q, but instead of holding the the "stretched" outputs, outputs a blip stream that emits every time the stretched  "progresses" (every n ticks)See  for more information. let a = stretchB 2 (accum (+) 0)streamAuto' a [1,8,5,4,3,7,2,0]A[Blip 1, NoBlip, Blip 6, NoBlip, Blip 9, NoBlip, Blip 11, NoBlip] Accelerates the , so instead of taking an a and returning a b, it takes a list of a, "streams" the ' over each one, and returns a list of b results."For example, if you normally feed sumFrom 0P a 1, then a 2, then a 3, you'd get a 1, then a 3, then a 6. But if you feed  (sumFrom 0) a [1,2], you'd get a [1,3], and if you fed it a [3] after, you'd get a [6].Turns a  [a] -> [b] into an [[a]] -> [[b]]&; if you "chunk up" the input stream a9s into chunks of input to feed all at once, the outputs b! will be chunked up the same way.)streamAuto' (sumFrom 0) [1,2,3,4,5,6,7,8][1,3,6,10,15,21,28,36]DstreamAuto' (accelOverList (sumFrom 0)) [[1,2],[],[3,4,5],[6],[7,8]]![[1,3],[],[6,10,15],[21],[28,36]]%Mostly useful if you want to feed an  multiple inputs in the same step. Note that if you always feed in singleton lists (lists with one item), you'll more or less get the same behavior as normal. n a turns an  a into an "accelerated" %, where every input is fed into the  n9 times. All of the results are collected in the output.!The same input is fed repeatedly n times..streamAuto' (accelerate 3 (sumFrom 0)) [2,3,4][[2,4,6],[9,12,15],[19,23,27]]$-- ^adding 2s ^adding 3s ^adding 4s xd n a is like  n a*, except instead of feeding in the input n= times, it feeds the input in once and repeats the "filler" xd) for the rest of the accelerating period.:streamAuto' (accelerateWith (-1) 3 (sumFrom 0)) [1,10,100] [[1,0,-1],[9,8,7],[107,106,105]] -- ^ feed in 1 once and -1 twice*-- ^ feed in 10 once and -1 twice3-- ^ feed in 100 once and -1 twice Takes an  that produces (b, > c), and turns it into an  that produces ([b], c).Basically, the new  "squishes together" the periods of output between each time the blip stream emits. All outputs between each emitted value are accumulated and returned in the resulting [b].%It "does this" in the same manner as  and K: first feed the input, then step repeatedly with the default input value.%let a :: Auto' Int (Int, Blip String) a = proc i -> do& sums <- sumFrom 0 -< iB blp <- every 3 -< i -- emits every 3 ticks.E id -< (sums, sums <& blp) -- replace emitted valueD -- with the running sum&let skipA :: Auto' Int ([Int], String) skipA = skipTo (-1) a&let (res1, skipA') = stepAuto' skipA 8res15([8,7,6], 6) -- fed 8 first, then (-1) repeatedly&let (res2, _ ) = evalAuto skipA' 5res25([11,10,9], 9) -- fed 5 first, then (-1) repeatedly^If the blip stream never emits then stepping this and getting the result or the next/updated ! never terminates...so watch out! Turns an N m a b into an  m a b --- that is, an  m a (Maybe b) into an  m a b.*It does this by "skipping over" all "off"/( input. When the result "should" be a , it re-runs the N= over and over again with the given default input until the # turns back "on" again (outputs a ).If the Nn reaches a point where it will never be "on" again, stepping this and getting the result or the next/updated ! won't terminate...so watch out!let a1 = offFor 3 . sumFrom 0streamAuto' a1 [1..10]6[Nothing, Nothing, Nothing, Just 10, Just 15, Just 21]%streamAuto' (fastForward 0 a1) [1..6][1,3,6,10,15,21])streamAuto' (fastForward (-10) a1) [1..6][-29,-27,-24,-20,-15,-9]SIn that last example, the first input is 1, then it inputs (-10) until it is "on"/C again (on the fourth step). Then continues imputing 2, 3, 4 etc.Same behavior as  , except accumulates all of the b c outputs in a list.*When first asked for output, "primes" the ~ first by streaming it with all of the given inputs first before processing the first input. Aterwards, behaves like normal.1streamAuto' (priming [1,2,3] (sumFrom 0)) [1..10][7,9,12,16,21,27,34,42,51,61]The . behaves as if it had already "processed" the [1,2,3]J, resulting in an accumulator of 6, before it starts taking in any input.%Normally this would be silly with an $, because the above is the same as:*let (_, a) = overList' (sumFrom 0) [1,2,3]streamAuto' a [1..10][7,9,12,16,21,27,34,42,51,61]:This becomes somewhat more useful when you have "monadic" As, and want to defer the execution until during normal stepping:9_ <- streamAuto (priming [1,2,3] (arrM print)) [10,11,12]1 -- IO effects23101112 initial value initial valuefunction to apply initial valuefunction to apply initial value initial value initial value$items to delay with (initial values)$items to delay with (initial values)number of steps to delayinitial value(s)number of steps to delayinitial value(s)stretching factor to stretchstretching factor to stretchstretching factor to stretch to accelerateacceleration factor to accelerate0default input value, during acceleration periodsacceleration factor to accelerate1default input value, during skipping periods9 to skip over, until each time the blip stream emits default inputN, to fastforward (past each "off" period, or ) default input to fast-forward (past each b)inputs to prime with to prime  s that represent collections of Fs that can be run in parallel, multiplexed, gathered...(c) Justin Le 2015MIT justin@jle.imunstableportableNoneDLORTGive a list of  m a b and get back an  m [a] [b] --- take a list of a 's and feed them to each of the s, and collects their output b's.CIf the input list doesn't have enough items to give to all of the ]s wrapped, then use the given default value. Any extra items in the input list are ignored..For an example, we're going to make a list of gs that output a running sum of all of their inputs, but each starting at a different beginning value: [summerList :: [Auto' Int Int] summerList = [sumFrom 0, sumFrom 10, sumFrom 20, sumFrom 30] Then, let's throw it into " with a sensible default value, 0: @summings0 :: Auto' [Int] [Int] summings0 = zipAuto 0 summerList Now let's try it out!3let (r1, summings1) = stepAuto' summings0 [1,2,3,4]r1[ 1, 12, 23, 34]/let (r2, summings2) = stepAuto' summings1 [5,5]r2[ 6, 17, 23, 34];let (r3, _ ) = stepAuto' summings2 [10,1,10,1,10000]r3[16, 18, 33, 35]Like , but delay the input by one step. The first input to all of them is the "default" value, and after that, feeds in the input streams delayed by one.Let's try the example from , except with  instead: summerList :: [Auto' Int Int] summerList = map sumFrom [0, 10, 20, 30] summings0 :: Auto' [Int] [Int] summings0 = dZipAuto 0 summerList Trying it out:3let (r1, summings1) = stepAuto' summings0 [1,2,3,4]r1[ 0, 10, 20, 30]/let (r2, summings2) = stepAuto' summings1 [5,5]r2[ 1, 12, 23, 34];let (r3, summings3) = stepAuto' summings2 [10,1,10,1,10000]r3[ 6, 17, 23, 34];let (r4, _ ) = stepAuto' summings3 [100,100,100,100]r4[16, 18, 33, 35],The non-serializing/non-resuming version of .Takes a bunch of 6s that take streams streams, and turns them into one N that takes a bunch of blip streams and feeds them into each of the original  s, in order.It's basically like \, except instead of taking in normal streams of values, it takes in blip streams of values.9If the input streams ever number less than the number of s zipped, the other (s are stepped assuming no emitted value.A delayed version of ,The non-serializing/non-resuming version of .A dynamic box of Ns. Takes a list of inputs to feed to each one, in the order that they were added. Also takes a blip stream, which emits with new Ns to add to the box.Add new N3s to the box however you want with the blip stream.As soon as an N turns "off", the N6 is removed from the box, and its output is silenced.eThe adding/removing aside, the routing of the inputs (the first field of the tuple) to the internal ,s and the outputs behaves the same as with .This will be a pretty powerful collection if you ever imagine adding and destroying behaviors dynamically...like spawning new enemies, or something like that.DLet's see an example...here we are going to be throwing a bunch of +s that count to five and then die into our ...once every other step. <-- count upwards, then die when you reach 5 countThenDie :: M@ () Int countThenDie = onFor 5 . iterator (+1) 1 -- emit a new  countThenDie, every two steps throwCounters :: Auto' () (> [M () Int]) throwCounters = tagBlips [countThenDie] . every 2 a :: Auto' () [Int] a = proc _ -> do newCounter <- throwCounters -< () dynZip_ () -< (repeat (), newCounter) !let (res, _) = stepAutoN' 15 a ()res [[], [1 ] , [2, ] , [3, 1 ] , [4, 2 ] , [5, 3, 1 ] , [ 4, 2 ] , [ 5, 3, 1 ] , [ 4, 2 ] , [ 5, 3, 1]]#This is a little unweildy, because zs maybe disappearing out of the thing while you are trying to feed inputs into it. You might be feeding an input to an ...but one of the Ss before it on the list has disappeared, so it accidentally goes to the wrong one..Because of this, it is suggested that you use (, which allows you to "target" labeled s with your inputs.This / is inherently unserializable, but you can use  for more or less the same functionality, with serialization possible. It's only slightly less powerful...for all intents and purposes, you should be able to use both in the same situations. All of the examples here can be also done with .Like ,, but instead of taking in a blip stream of N's directly, takes in a blip stream of ks to trigger adding more N s to the "box", using the given k -> N m a b function to make the new N to add. Pretty much all of the power of , but with serialization.See  for examples and caveats.0You could theoretically recover the behavior of  with  id, if there wasn't a p constraint on the k.,The non-serializing/non-resuming version of '. Well, you really might as well use , which is more powerful...but maybe using this can inspire more disciplined usage. Also works as a drop-in replacement for .A dynamic box of s, indexed by an e . Takes an - of inputs to feed into their corresponding 2s, and collect all of the outputs into an output .Whenever any of the internal  s return (, they are removed from the collection. "import qualified Data.IntMap as IM0let dm0 :: Auto' (IM.IntMap Int) (IM.IntMap Int) dm0 = proc x -> doA initials <- immediately -< [ Just <$> sumFrom 0D , Just <$> sumFrom 10 ]D newIs <- every 3 -< [ Just <$> sumFrom 0 ]> dynMap_ (-1) -< (x, initials `mergeL` newIs)&let (res1, dm1) = stepAuto' dm0 memptyres1fromList [(0, -1), (1, 9)]>let (res2, dm2) = stepAuto' dm1 (IM.fromList [(0,100),(1,50)])res2fromList [(0, 99), (1, 59)]<let (res3, dm3) = stepAuto' dm2 (IM.fromList [(0,10),(1,5)])res3%fromList [(0, 109), (1, 64), (2, -1)];let (res4, _ ) = stepAuto' dm3 (IM.fromList [(1,5),(2,5)])res4$fromList [(0, 108), (1, 69), (2, 4)]!One quirk is that every internal 5 is "stepped" at every step with the default input;  is a version of this where s that do not have a corresponding "input" are left unstepped, and their last output preserved in the aggregate output. As such,  might be seen more often.This / is inherently unserializable, but you can use  for more or less the same functionality, with serialization possible. It's only slightly less powerful...for all intents and purposes, you should be able to use both in the same situations. All of the examples here can be also done with .Like ,, but instead of taking in a blip stream of N's directly, takes in a blip stream of ks to trigger adding more N s to the "box", using the given k -> N m a b function to make the new N to add. Pretty much all of the power of , but with serialization.See  for examples and use cases.0You could theoretically recover the behavior of  with  id, if there wasn't a p constraint on the k.,The non-serializing/non-resuming version of '. Well, you really might as well use , which is more powerful...but maybe using this can inspire more disciplined usage. Also works as a drop-in replacement for .* multiplexer. Stores a bunch of internal Us indexed by a key. At every step, takes a key-input pair, feeds the input to the + stored at that key and outputs the output.&If the key given does not yet have an ( stored at that key, initializes a new , at that key by using the supplied function.Once initialized, these s are stored there forever./You can play around with some combinators from Control.Auto.Switch; for example, with resetOn, you can make 8s that "reset" themselves when given a certain input.  switchOnF, could be put to use here too in neat ways.let mx0 = mux (\_ -> sumFrom 0),let (res1, mx1) = stepAuto' mx0 ("hello", 5)res15,let (res2, mx2) = stepAuto' mx1 ("world", 3)res23,let (res3, mx3) = stepAuto' mx2 ("hello", 4)res39DstreamAuto' mx3 [("world", 2), ("foo", 6), ("foo", 1), ("hello", 2)] [5, 6, 7, 11],The non-serializing/non-resuming version of . multiplexer, like ', except allows update/access of many os at a time. Instead of taking in a single key-value pair and outputting a single result, takes in an entire # of key-value pairs and outputs a  of key-result pairs.import qualified Data.Map as Mlet mx0 = mux (\_ -> sumFrom 0):let (res1, mx1) = stepAuto' mx0 (M.fromList [ ("hello", 5)A , ("world", 3) ])res1%fromList [("hello", 5), ("world", 3)]:let (res2, mx2) = stepAuto' mx1 (M.fromList [ ("hello", 4)A , ("foo" , 7) ])res2#fromList [("foo", 7), ("hello", 9)]=let (res3, _ ) = mx2 (M.fromList [("world", 3), ("foo", 1)])res3#fromList [("foo", 8), ("world", 6)]See  for more notes.,The non-serializing/non-resuming version of .Like  , but holds Ns instead. When any given N turns "off", it's removed from the collection. If its key is fed in again, it'll be restarted with the initializing function. On the actual step when it turns "off",  will be returned.,The non-serializing/non-resuming version of .Like  , but holds Ns instead. When any given N7 turns "off", it's removed from the collection. Only N>s that are "on" after the step will be present in the output .,The non-serializing/non-resuming version of .Keeps an internal  of NCs and, at every step, the output is the last seen output of every N, indexed under the proper key..At every step, the input is a key-value pair; $ will feed that input value to the NF under the proper key and update the output map with that new result.jIf the key offered the input is not yet a part of the collection, initializes it with the given function.Any N that turns "off" (outputs ) from this will be immediately removed from the collection. If something for that key is received again, it will re-initialize it. !let sumUntil :: Interval' Int Int sumUntil = proc x -> do1 sums <- sumFrom 0 -< x4 stop <- became (> 10) -< sums- before -< (sums, stop)= -- (a running sum, "on" until the sum is greater than 10)!let gt0 = gather (\_ -> sumUntil),let (res1, gt1) = stepAuto' gt0 ("hello", 5)res1fromList [("hello", 5)],let (res2, gt2) = stepAuto' gt1 ("world", 7)res2%fromList [("hello", 5), ("world", 7)]*let (res3, gt3) = stepAuto' gt2 ("foo", 4)res31fromList [("foo", 4), ("hello", 5), ("world", 7)],let (res4, gt4) = stepAuto' gt3 ("world", 8)res4#fromList [("foo", 4), ("hello", 5)]DstreamAuto' gt4 [("world", 2),("bar", 9),("world", 6),("hello", 11)]3[ fromList [("foo", 4), ("hello", 5), ("world", 2)]?, fromList [("bar", 9), ("foo", 4), ("hello", 5), ("world", 2)]?, fromList [("bar", 9), ("foo", 4), ("hello", 5), ("world", 8)]1, fromList [("bar", 9), ("foo", 4), ("world", 8)]]BIn practice this ends up being a very common collection; see the  'https://github.com/mstksg/auto-examples auto-examples project for many examples!Because everything needs a key@, you don't have the fancy "auto-generate new keys" feature of dynMap2...however, you could always pull a new key from perBlip  enumFromA or something. Like with , combinators from Control.Auto.Switch like resetOn and  switchOnF are very useful here!,The non-serializing/non-resuming version of :Does serialize the actual s themselves; the Hs are all serialized and re-loaded/resumed when 'gather_ f' is resumed.Does not* serialize the "last outputs", so resumed ps that have not yet been re-run/accessed to get a fresh output are not represented in the output map at first.-The non-serializing/non-resuming vervsion of :Serializes neither the Qs themselves nor the "last outputs" --- essentially, serializes/resumes nothing. Much like a, except allows you to pass in multiple key-value pairs every step, to update multiple internal s. import qualified Data.Map as M!let sumUntil :: Interval' Int Int sumUntil = proc x -> do1 sums <- sumFrom 0 -< x4 stop <- became (> 10) -< sums- before -< (sums, stop)= -- (a running sum, "on" until the sum is greater than 10)%let gm0 = gatherMany (\_ -> sumUntil):let (res1, gm1) = stepAuto' gm0 (M.fromList [ ("hello", 5)> , ("world", 7)2 ])res1%fromList [("hello", 5), ("world", 7)]8let (res2, gm2) = stepAuto' gm1 (M.fromList [ ("foo", 4)> , ("hello", 3)2 ])res21fromList [("foo", 4), ("hello", 8), ("world", 7)]:let (res3, gm3) = stepAuto' gm2 (M.fromList [ ("world", 8)< , ("bar", 9)2 ])res3/fromList [("bar", 9), ("foo", 4), ("hello", 8)]:let (res4, _ ) = stepAuto' gm3 (M.fromList [ ("world", 2)= , ("bar", 10)2 ])res41fromList [("foo", 4), ("hello", 8), ("world", 2)]See  for more notes.,The non-serializing/non-resuming version of :Does serialize the actual s themselves; the Ls are all serialized and re-loaded/resumed when 'gatherMany_ f' is resumed.Does not* serialize the "last outputs", so resumed ps that have not yet been re-run/accessed to get a fresh output are not represented in the output map at first.-The non-serializing/non-resuming vervsion of :Serializes neither the Qs themselves nor the "last outputs" --- essentially, serializes/resumes nothing.)default input value s to zip updefault input value s to zip updefault input value s to zip up s to zip up s to zip up s to zip up function to generate a new N for each coming k in the blip stream."default" input to feed in function to generate a new N for each coming k in the blip stream."default" input to feed in"default" input to feed in function to generate a new N for each coming k in the blip stream."default" input to feed in function to generate a new N for each coming k in the blip stream."default" input to feed infunction to create a new ' if none at that key already exists.function to create a new & if none at that key already existsfunction to create a new & if none at that key already existsfunction to create a new & if none at that key already existsf : make new Autosgo: make next stepas: all current Autos xs: InputsOutputs, and next Auto.function to create a new ' if none at that key already exists.function to create a new & if none at that key already existsfunction to create a new & if none at that key already existsfunction to create a new & if none at that key already existsf : make new Autosgo: make next stepas: all current Autos xs: InputsOutputs, and next Auto.function to create a new ) if none at that key already existsfunction to create a new ) if none at that key already existsfunction to create a new & if none at that key already existsfunction to create a new & if none at that key already existsfunction to create a new & if none at that key already existsfunction to create a new & if none at that key already exists)3Tools for generating and manipulating blip streams.(c) Justin Le 2015MIT justin@jle.imunstableportableNone$?PMerge all the blip streams together into one, favoring the first emitted value.OMerge all the blip streams together into one, favoring the last emitted value.eMerge all of the blip streams together, using the given merging function associating from the right. DEPRECATED: In its current form,  will disappear in 0.5. The new version will be: .foldrB :: (a -> a -> a) -> [Blip a] -> Blip b hWhich will not emit if nothing emits. This really was supposed to be the intended behavior originally.|For this reason, please do not use this anymore. As it is currently implemented, it doesn't really make any sense, either.-To begin using the new behavior, you can use: foldr (merge f) mempty dMerge all of the blip streams together, using the given merging function associating from the left. DEPRECATED: In its current form,  will disappear in 0.5. The new version will be: /foldlB' :: (a -> a -> a) -> [Blip a] -> Blip b hWhich will not emit if nothing emits. This really was supposed to be the intended behavior originally.|For this reason, please do not use this anymore. As it is currently implemented, it doesn't really make any sense, either.-To begin using the new behavior, you can use: foldl' (merge f) mempty  Takes two 1s producing blip streams and returns a "merged" ( that emits when either of the original Ks emit. When both emit at the same time, the left (first) one is favored. a1 <& a2 == mergeL <$> a1 <*> a2 Takes two 1s producing blip streams and returns a "merged" ( that emits when either of the original Ms emit. When both emit at the same time, the right (second) one is favored. a1 &> a2 == mergeR <$> a1 <*> a2An @ that ignores its input and produces a blip stream never emits.cProduces a blip stream that emits with the first received input value, and never again after that.Often used with : immediately . pure "Emit me!"Or, in proc notation:  blp <- immediately -< "Emit me!"dto get a blip stream that emits a given value (eg., "Emit me!") once and stops emitting ever again.2streamAuto' (immediately . pure "Emit me!") [1..5]1[Blip "Emit Me!", NoBlip, NoBlip, NoBlip, NoBlip]qProduces a blip stream that only emits once, with the input value on the given step number. It emits the input on that many steps.immediately == inB 1 n emits every n steps, emitting with the n last items received. streamAuto' (collectN 3) [1..10]<[ NoBlip, NoBlip, Blip [1,2,3], NoBlip, NoBlip, Blip [4,5,6](, NoBlip, NoBlip, Blip [7,8,9], NoBlip ],The non-serializing/non-resuming version of A blip stream that listens to an input blip stream and emits after the input stream emits a given number of times. Emits with a list of all received emitted values.,The non-serializing/non-resuming version of .bProduces a blip stream that emits the input value whenever the input satisfies a given predicate.Warning! This C has the capability of "breaking" blip semantics. Be sure you know what you are doing when using this. Blip streams are semantically supposed to only emit at discrete, separate occurrences. Do not use this for interval-like (on and off for chunks at a time) things; each input should be dealt with as a separate thing. For interval semantics, we have Interval from Control.Auto.Interval. Good example: D-- is only emitting at discrete blips emitOn even . iterator (+ 1) 0 Bad examples: r-- is emitting for "durations" or "intervals" of time. emitOn (< 10) . iterator (+ 1) 0 emitOn (const True) . foo.These bad examples would be good use cases of Interval.0Can be particularly useful with prisms from the lens package, where things like emitOn (has _Right) and emitOn (hasn't _Right) will emit the input  Either a b whenever it is or isn't a . See  for more common uses with lens.An ! that runs every input through a a ->  bD test and produces a blip stream that emits the value inside every  result.)Particularly useful with prisms from the lens package, where things like emitJusts (preview _Right) will emit the b whenever the input  Either a b stream is a Right.-Warning! Carries all of the same dangers of . You can easily break blip semantics with this if you aren't sure what you are doing. Remember to only emit at discrete, separate occurences, and not for interval-like (on and off for chunks at a time) things. For interval semantics, we have Control.Auto.Interval.See the examples of & for more concrete good/bad use cases. n is an / that emits with the incoming inputs on every n/th input value. First emitted value is on the nth step.7Will obviously break blip semantics when you pass in 1. n xs is an N that ignores its input and creates a blip stream that emits each element of xs one at a time, evey n) steps. First emitted value is at step n..Once the list is exhausted, never emits again.3Obviously breaks blip semantics when you pass in 1.-The process of serializing and resuming this , is O(n) space and time with the length of xsL. So don't serialize this if you plan on passing an infinite list :) See Control.Auto.Generate for more options..eachAt n xs == perBlip (fromList xs) . every n-The non-serializing/non-resumable version of .QSuppress all upstream emissions when the predicate (on the emitted value) fails.Splits a blip stream based on a predicate. Takes in one blip stream and produces two: the first emits whenever the input emits with a value that passes the predicate, and the second emits whenever the input emits with a value that doesn't.Splits1 a blip stream based on a predicate returning an . All b0 results go to the first output stream, and all  results go to the second.2On an 'a -> Either () b', is roughly analogous to 7. On an 'a -> Either () ()', is roughly analogous to  or . Collapsesk a blip stream of blip streams into single blip stream. that emits whenever the inner-nested stream emits.oWaits on two streams, and emits with the first seen items when both have emitted. Once it emits, starts over.NstreamAuto' collectB [(Blip 1, NoBlip), (Blip 2, Blip 'a'),(Blip 3, Blip 'b')]&[NoBlip, Blip (1, 'a'), Blip (3, 'b')]3Can be used to implement a sort of "parallel wait".,The non-serializing/non-resuming version of .eApplies the given function to every emitted value, and suppresses all those for which the result is :. Otherwise, lets it pass through with the value in the .>Supress all upstream emitted values except for the very first.`Suppress only the first emission coming from upstream, and let all the others pass uninhibited. n allows only the first n3 emissions to pass; it suppresses all of the rest.JAllow all emitted valuesto pass until the first that fails the predicate. n suppresses the first nB emissions from upstream and passes through the rest uninhibited.nSuppress all emited values until the first one satisfying the predicate, then allow the rest to pass through.dTakes in a blip stream and outputs a blip stream where each emission is delayed/lagged by one step.2streamAuto' (emitOn (\x -> x `mod` 3 == 0)) [1..9]H[NoBlip, NoBlip, Blip 3, NoBlip, NoBlip, Blip 6, NoBlip, NoBlip, Blip 9]=streamAuto' (lagBlips . emitOn (\x -> x `mod` 3 == 0)) [1..9]H[NoBlip, NoBlip, NoBlip, Blip 3, NoBlip, NoBlip, Blip 6, NoBlip, NoBlip],The non-serializing/non-resuming version of .pAccumulates all emissions in the incoming blip stream with a "folding function", with a given starting value.  b -> a -> b, with a starting b, gives  m (> a) (> b).iThe resulting blip stream will emit every time the input stream emits, but with the "accumulated value". Basically %, but on blip stream emissions.#accumB f x0 == perBlip (accum f x0),The non-serializing/non-resuming version of .}The output is the result of folding up every emitted value seen thus far, with the given folding function and initial value.'scanB f x0 == holdWith x0 . accumB f x0&let a = scanB (+) 0 . eachAt 2 [1,2,3]"take 8 . streamAuto' a $ repeat ()[0, 1, 1, 3, 3, 6, 6, 6, 6],The non-serializing/non-resuming version of .The output is the 3 (monoid sum) of all emitted values seen this far.,The non-serializing/non-resuming version of . ZThe output is the number of emitted values received from the upstream blip stream so far. Blip stream that emits whenever the predicate applied to the input switches from false to true. Emits with the triggering input value. Blip stream that emits whenever the predicate applied to the input switches from true to false. Emits with the triggering input value. Blip stream that emits whenever the predicate applied to the input switches from true to false or false to true. Emits with the triggering input value. -The non-serializing/non-resumable version of  .-The non-serializing/non-resumable version of  .-The non-serializing/non-resumable version of  .Like  9, but emits a '()' instead of the triggering input value.BUseful because it can be serialized without the output needing a p instance.Like  :, but emits a '()' instead of the triggering input value.BUseful because it can be serialized without the output needing a p instance.Like  , but emits a 5 instead of the triggering input value. An emitted l< indicates that the predicate just became true; an emitted k0 indicates that the predicate just became false.BUseful because it can be serialized without the output needing a p instance.SBlip stream that emits whenever the input value changes. Emits with the new value.Warning: Note that, when composed on a value that is never expected to keep the same value twice, this technically breaks blip semantics.-The non-serializing/non-resumable version of .An # that emits whenever it receives a # input, with the value inside the .-Warning! Carries all of the same dangers of . You can easily break blip semantics with this if you aren't sure what you are doing. Remember to only emit at discrete, separate occurences, and not for interval-like (on and off for chunks at a time) things. For interval semantics, we have Control.Auto.Interval.See the examples of & for more concrete good/bad use cases.onJusts == emitJusts idLike >, except forks into two streams depending on if the input is b or .'Is only meaningful if you expect every 'Left'/'Right'' choice to be independent of the last.onEithers == emitEithers idLike J, except forks into two streams depending on the function's result being b or .'Is only meaningful if you expect every 'Left'/'Right'' choice to be independent of the last. d is an D that decomposes the incoming blip stream by constantly outputting dK except when the stream emits, and outputs the emitted value when it does. d f is an D that decomposes the incoming blip stream by constantly outputting dC except when the stream emits, and outputs the result of applying f# to the emitted value when it does.Collapse a blip stream of as into a stream of `Maybe a`'sTake in a normal stream and a blip stream. Behave like the normal stream when the blip stream doesn't emit...but when it does, output the emitted value instead. y0 is an u whose output is always the /most recently emitted/ value from the input blip stream. Before anything is emitted, y0 is outputted as a placeholder.Contrast with hold from Control.Auto.Interval.+A non-serializing/non-resumable version of .aRe-emits every emission from the input blip stream, but replaces its value with the given value.#tagBlips x == modifyBlips (const x)iRe-emits every emission from the input blip stream, but applies the given function to the emitted value.  Takes an  m a b (an  that turns incoming as into outputting b s) into an  m (> a) (> b); the original D is lifted to only be applied to emitted contents of a blip stream.$When the stream emits, the original j is "stepped" with the emitted value; when it does not, it is paused and frozen until the next emission.let sums = perBlip (sumFrom 0)let blps = eachAt 2 [1,5,2]%take 8 . streamAuto' blps $ repeat ()@[NoBlip, Blip 1, NoBlip, Blip 5, NoBlip, Blip 2, NoBlip, NoBlip].take 8 . streamAuto' (sums . blps) $ repeat ()@[NoBlip, Blip 1, NoBlip, Blip 6, NoBlip, Blip 8, NoBlip, NoBlip]F(number of steps before value is emitted.predicate to emit on"predicate" to emit on. emit every n steps. emit every n stepslist to emit values from emit every n stepslist to emit values fromfiltering predicate$number of emissions to allow to passfiltering predicate)number of emissions to suppress initiallyfiltering predicatefolding function initial valuefolding function initial valuefolding function initial valuefolding function initial value  change condition change condition change condition change conditionchange conditionchange conditionchange conditionchange conditionchange condition@the "default value" to output when the input is not emitting.@the 'default value" to output when the input is not emitting.Ithe function to apply to the emitted value whenever input is emitting.)value to replace every emitted value with&function to modify emitted values with C>ACD      C> ACD     F      55QAccessing, executing, and manipulating underyling monadic effects.(c) Justin Le 2015MIT justin@jle.imunstableportableNoneL!The very first output executes a monadic action and uses the result as the output, ignoring all input. From then on, it persistently outputs that first result.Like #B, except outputs the result of the action instead of ignoring it.JUseful for loading resources in IO on the "first step", like a word list: ;dictionary :: Auto IO a [String] dictionary = cache (lines  $ readFile "wordlist.txt") ".The non-resumable/non-serializable version of !. Every time the S is deserialized/reloaded, it re-executes the action to retrieve the result again.Useful in cases where you want to "re-load" an expensive resource on every startup, instead of saving it to in the save states. <dictionary :: Auto IO a [String] dictionary = cache_ (lines  $ readFile "dictionary.txt") #]Always outputs '()', but when asked for the first output, executes the given monadic action.Pretty much like !, but always outputs '()'.$.The non-resumable/non-serializable version of #. Every time the ; is deserialized/reloaded, the action is re-executed again.%The input stream is a stream of monadic actions, and the output stream is the result of their executions, through executing them.&Applies the given "monadic function" (function returning a monadic action) to every incoming item; the result is the result of executing the action returned.>Note that this essentially lifts a "Kleisli arrow"; it's like arr;, but for "monadic functions" instead of normal functions: Barr :: (a -> b) -> Auto m a b arrM :: (a -> m b) -> Auto m a b !arrM f . arrM g == arrM (f <=< g)HOne neat trick you can do is that you can "tag on effects" to a normal  by using g from Control.Applicative. For example:let a = arrM print *> sumFrom 0ys <- streamAuto a [1..5]1 -- IO output2345ys[1,3,6,10,15] -- the resultHere, a behaves "just like" sumFrom 0y...except, when you step it, it prints out to stdout as a side-effect. We just gave automatic stdout logging behavior!'Maps one blip stream to another; replaces every emitted value with the result of the monadic function, executing it to get the result.(Maps one blip stream to another; replaces every emitted value with the result of a fixed monadic action, run every time an emitted value is received.)Outputs the identical blip stream that is received; however, every time it sees an emitted value, executes the given monadic action on the side.*Unrolls the underlying  of an  into an T that takes in the input "environment" every turn in addition to the normal input.So you can use any  r m as if it were an m;. Useful if you want to compose and create some isolated Is with access to an underlying environment, but not your entire program.6Also just simply useful as a convenient way to use an  over Reader with   and friends.When used with Reader r, it turns an  (Reader r) a b into an  (a, r) b.+ Takes an o that operates under the context of a read-only environment, an environment value, and turns it into a normal 5 that always "sees" that value when it asks for one.+let a = effect ask :: Auto (Reader b) a b.let rdr = streamAuto' a [1..5] :: Reader b [b]runReader rdr "hey"#["hey", "hey", "hey", "hey", "hey"]7Useful if you wanted to use it inside/composed with an * that does not have a global environment: rbar :: Auto' Int String bar = proc x -> do hey <- sealReader (effect ask) "hey" -< () id -< hey ++ show x streamAuto' bar [1..5](["hey1", "hey2", "hey3", "hey4", "hey5"],Note that this version serializes the given r& environment, so that every time the < is reloaded/resumed, it resumes with the originally given r environment, ignoring whatever rW is given to it when trying to resume it. If this is not the behavior you want, use ,.Reader? is convenient because it allows you to "chain" and "compose" vs with a common environment, instead of explicitly passing in values every time. For a convenient way of generating  s under -, and also for some motivating examples, see / and *.,,The non-resuming/non-serializing version of +". Does not serialize/reload the r1 environment, so that whenever you "resume" the , it uses the new rS given when you are trying to resume, instead of loading the originally given one.DOES serialize the actual !- Takes an o that operates under the context of a read-only environment, an environment value, and turns it into a normal d that always gets its environment value by executing an action every step in the underlying monad.This can be abused to write unmaintainble code really fast if you don't use it in a disciplined way. One possible usage is to query a database in  (or o) for a value at every step. If you're using underlying global state, you can use it to query that too, with  or gets. You could even use >, maybe, to get the result from standard input at every step.'One disciplined wrapper around this is .=, where the environment at every step comes from reading an 7. This can be used to "hot swap" configuration files.. Takes an o that operates under the context of a read-only environment, an environment value, and turns it into a normal 1 that always gets its environment value from an .This allows for "hot swapping" configurations. If your whole program runs under a configuration data structure as the environment, you can load the configuration data to the ? and then "hot swap" it out by just changing the value in the  from a different thread.4Note that this will block on every "step" until the  is readablefullhas a value, if it does not.+Basically a disciplined wrapper/usage over -./Transforms an 1 on two input streams ( a "normal input" stream a# and an "environment input stream" r ) into an  on one input stream a with an underlying environment r through a Reader monad./Why is this useful? Well, if you have several s that all take in a side rF stream, and you want to convey that every single one should get the same rc at every step, you can instead have all of them pull from a common underlying global environment.!Note: Function is the inverse of *: / . * == h * . / == h 0Unrolls the underlying  w m [ , so that an  that takes in a stream of a and outputs a stream of b will now output a stream (b, w), where w% is the "new log" of the underlying Writer at every step. Examples: ]foo :: Auto (Writer (Sum Int)) Int Int foo = effect (tell 1) *> effect (tell 1) *> sumFrom 0 let fooWriter = streamAuto foorunWriter $ fooWriter [1..10]&([1,3,6,10,15,21,28,36,45,55], Sum 20)fooy increments an underlying counter twice every time it is stepped; its "result" is just the cumulative sum of the inputs.When we "stream" it, we get a  [Int] -> Writer (Sum Int) [Int]'...which we can give an input list and  runWriterb it, getting a list of outputs and a "final accumulator state" of 10, for stepping it ten times.However, if we use 0 before streaming it, we get:let fooW = runWriterA foostreamAuto' fooW [1..10]'[ (1 , Sum 2), (3 , Sum 2), (6 , Sum 2)/, (10, Sum 2), (15, Sum 2), (21, Sum 2), -- ...@Instead of accumulating it between steps, we get to "catch" the Writer" output at every individual step.!We can write and compose our own s under WriterR, using the convenience of a shared accumulator, and then "use them" with other s: \bar :: Auto' Int Int bar = proc x -> do (y, w) <- runWriterA foo -< x blah <- blah -< w 9And now you have access to the underlying accumulator of foo to access. There, w8 represents the continually updating accumulator under foo0, and will be different/growing at every "step".For a convenient way to create an  under , see 1.1Transforms an 7 on with two output streams (a "normal output stream" b , and a "logging output stream" w ) into an  with just one output stream a, funneling the logging stream w into an underlying  monad.!Note: Function is the inverse of 0: 1 . 0 == h 0 . 1 == h 2 Takes an e that works with underlying global, mutable state, and "seals off the state" from the outside world.,An 'Auto (StateT s m) a b' maps a stream of a to a stream of b6, but does so in the context of requiring an initial s& to start, and outputting a modified s.Consider this example State : foo :: Auto (State Int) Int Int foo = proc x -> do execB (modify (+1)) . emitOn odd -< x execB (modify (*2)) . emitOn even -< x st <- effect get -< () sumX <- sumFrom 0 -< x id -< sumX + st vOn every output, the "global" state is incremented if the input is odd and doubled if the input is even. The stream st: is always the value of the global state at that point. sumX} is the cumulative sum of the inputs. The final result is the sum of the value of the global state and the cumulative sum.In writing like this, you lose some of the denotative properties because you are working with a global state that updates at every output. You have some benefit of now being able to work with global state, if that's what you wanted I guess.To "run" it, you could use  streamAuto to get a State Int Int:0let st = streamAuto foo [1..10] :: State Int Int runState st 50([ 7, 15, 19, 36, 42, 75, 83,136,156,277], 222)G(The starting state is 5 and the ending state after all of that is 222)However, writing your entire program with global state is a bad bad idea! So, how can you get the "benefits" of having small parts like foo be written using State>, and being able to use it in a program with no global state?Using 2L! Write the part of your program that would like shared global state with StateC...and compose it with the rest as if it doesn't, locking it away! YsealState :: Auto (State s) a b -> s -> Auto' a b sealState foo 5 :: Auto' Int Int  lbar :: Auto' Int (Int, String) bar = proc x -> do food <- sealState foo 5 -< x id -< (food, show x) streamAuto' bar [1..10]E[ (7, "1"), (15, "2"), (19, "3"), (36, "4"), (42, "5"), (75, "6") ... We say that 2 f s0[ takes an input stream, and the output stream is the result of running the stream through f", first with an initial state of s0., and afterwards with each next updated state.If you wanted to "seal" the state and have it be untouchable to the outside world, yet still have a way to "monitor"/"view" it, you can modify the original  using &&&, w), and 'get to get a "view" of the state:6streamAuto' (sealState (foo &&& effect get) 5) [1..10]U[(7,6),(15,12),(19,13),(36,26),(42,27),(75,54),(83,55),(146,110),(156,111),(277,222)]Now, every output of 2 foo 57 is tuplied up with a peek of its state at that point.&For a convenient way of "creating" an  under  in the first place, see 5.3,The non-resuming/non-serializing version of 2.4Unrolls the underlying  of an  into an  that takes in an input state every turn (in addition to the normal input) and outputs, along with the original result, the modified state.So now you can use any  s m as if it were an m;. Useful if you want to compose and create some isolated Cs with access to an underlying state, but not your entire program.6Also just simply useful as a convenient way to use an  over State with   and friends.When used with State s, it turns an  (State s) a b into an  (a, s) (b, s).&For a convenient way to "generate" an  , see 55Transforms an B with two input streams and two output streams (a "normal" input a output b; stream, and a "state transforming" side-stream taking in s and outputting s), abstracts away the s+ stream as a modifcation to an underyling ? monad. That is, your normal inputs and outputs are now your only% inputs and outputs, and your input sA comes from the underlying global mutable state, and the output s4 goes to update the underlying global mutable state.'For example, you might have a bunch of -s that interact with a global mutable state: xfoo :: Auto (StateT Double m) Int Bool bar :: Auto (StateT Double m) Bool Int baz :: Auto (StateT Double m) Bool String Where foo, bar, and bazC all interact with global mutable state. You'd use them like this: full :: Auto (StateT Double m) Int String full = proc inp -> do fo <- foo -< inp br <- bar -< fo bz <- baz -< fo id -< replicae br bz 5 allows you generate a new Auto under : ]thing :: Auto m (Int, Double) (Bool, Double) stateA thing :: Auto (StateT Double m) Int Bool OSo now the two side-channels are interpreted as working with the global state: full :: Auto (StateT Double m) Int String full = proc inp -> do fo <- foo -< inp tg <- stateA thing -< inp br <- bar -< fo || tg bz <- baz -< fo && tg id -< replicae br bz You can then "seal it all up" in the end with an initial state, that keeps on re-running itself with the resulting state every time: <full' :: Double -> Auto m Int String full' = sealState full rAdmittedly, this is a bit more esoteric and dangerous (programming with global state? what?) than its components / and 1; I don't actually recommend you programming with global state unless it really is the best solution to your problem...it tends to encourage imperative code/loops, and "unreasonable" and manageable code. See documentation for  sealStateA for best practices. Basically every bad thing that comes with global mutable state. But, this is provided here for sake of completeness with / and 1.!Note: function is the inverse of  runstateA. 5 . 4 == h 4 . 5 == h 6Like 54, but assumes that the output is the modified state.7Unrolls the underlying [ of an  if it happens to be  ('[]', , etc.).It can turn, for example, an  [] a b into an  a [b]3; it collects all of the results together. Or an   a b into an  a ( b).OThis might be useful if you want to make some sort of "underlying inhibiting" 7 where the entire computation might just end up being N in the end. With this, you can turn that possibly-catastrophically-failing  (with an underlying [ of ) into a normal , and use it as a normal  in composition with other s...returning  if your computation succeeded. 7 ::   a b ->  Interval' a b  Cfoo :: Auto Maybe Int Int foo = arrM $ x -> if even x then Just (x < 2) else Nothing bar :: Auto Maybe Int Int bar = arrM Just streamAuto foo [2,4,6,7]Nothing+streamAuto' (runTraversableA foo) [2,4,6,7]![Just 1, Just 2, Just 3, Nothing] streamAuto (foo &&& bar) [2,4,6]Just [(1, 2),(2, 4),(3, 6)]"streamAuto (foo &&& bar) [2,4,6,7]NothingDstreamAuto' (runTraversableA foo <|?> runTraversableA bar) [2,4,6,7] [Just 1, Just 2, Just 3, Just 7]8!Wraps a "try" over an underlying b monad; if the Auto encounters a runtime exception while trying to "step" itself, it'll output a b with the . Otherwise, will output left.[Note that you have to explicitly specify the type of the exceptions you are catching; see Control.Exception documentation for more details.!/monadic action to execute and use the result of"/monadic action to execute and use the result of#*monadic action to execute; result discared$*monadic action to execute; result discared%&monadic function'()* run over global environment receiving environments+ run over Readerthe perpetual environment, run over Readerthe perpetual environment- run over Readeraction to draw new r at every step. run over Reader containing an r for every step/ receiving an environment. run over an environment.01$ with a "normal" output stream bs and a "logging" stream ws under an underlying  , logging ws2 run over State initial state3 run over State initial state4 run over a state transformer1 whose inputs and outputs are a state transformer56 whose inputs and outputs are a state transformer run over a state transformer6; taking inputs and states and returning updated states over a state transformer7 run over traversable structure returning traversable structure8<Auto over IO, expecting an exception of a secific type.w!"#$%&'()*+,-./012345678&w%'()!#"$*+,/.-102345678!"#$%&'()*+,-./012345678 Entropy generationg s.(c) Justin Le 2015MIT justin@jle.imunstableportableNone93Given a seed-consuming generating function of form  g -> (b, g) (where g is the seed, and b0 is the result) and an initial seed, return an N that continually generates random values using the given generating funcion.5You'll notice that most of the useful functions from  System.Random fit this form:  ::  g => g -> (b, g)  ::  g => (b, b) -> (g -> (b, g))  If you are using something from  .http://hackage.haskell.org/package/MonadRandom MonadRandom, then you can use the runRand function to turn a Rand g b into a  g -> (b, g): runRand ::  g => Rand g b -> (g -> (b, g)) Here is an example using : (for ), but 9( works exactly the same way, I promise!let g = mkStdGen 86753093let a = stdRands (randomR (1,100)) g :: Auto' a Int!let (res, _) = stepAutoN' 10 a ()res([67, 15, 97, 13, 55, 12, 34, 86, 57, 42]Yeah, if you are using  from  System.Random, you'll notice that  has no pB instance, so you can't use it with this; you have to either use : or ;1 (if you don't want serialization/resumability).In the context of these generators, resumability basically means deterministic behavior over re-loads...if "reloading", it'll ignore the seed you pass in, and use the original seed given when originally saved.:Like 9, but specialized for  from  System.RandomA, so that you can serialize and resume. This is needed because  doesn't have a p instance.See the documentation of 9 for more information on this .;,The non-serializing/non-resuming version of 9.<Like 91, except taking a "monadic" random seed function g -> m (b, g) , instead of  g -> (b, g)G. Your random generating function has access to the underlying monad.!If you are using something from  .http://hackage.haskell.org/package/MonadRandom MonadRandom, then you can use the  function to turn a  g m b into a g -> m (b, g):  :: ([ m,  g) =>  g m b -> (g -> m (b, g)) =Like <, but specialized for  from  System.RandomA, so that you can serialize and resume. This is needed because  doesn't have a p instance.See the documentation of < for more information on this .>,The non-serializing/non-resuming version of <.?Takes a "random function", or "random arrow" --- a function taking an input value and a starting seed/entropy generator and returning a result and an ending seed/entropy generator --- and turns it into an ` that feeds its input into such a function and outputs the result, with a new seed every time.let f x = randomR (0 :: Int, x)4streamAuto' (arrRandStd f (mkStdGen 782065)) [1..10])-- [1,2,3,4,5,6,7,8,9,10] <- upper bounds@ [1,2,0,1,5,3,7,6,8,10] -- random number from 0 to upper bound!If you are using something from  .http://hackage.haskell.org/package/MonadRandom MonadRandom, then you can use the (runRand .) function to turn a a -> Rand g b into a a -> g -> (b, g): (runRand .) ::  g => (a -> Rand g b) -> (a -> g -> (b, g)) (This is basically , specialized.)@Like ?v, except the result is the result of a monadic action. Your random arrow function has access to the underlying monad.!If you are using something from  .http://hackage.haskell.org/package/MonadRandom MonadRandom, then you can use the ( .) function to turn a a ->  m g b into a a -> g -> m (b, g): ( .) ::  g => (a ->  g b) -> (a -> g -> m (b, g)) ALike ?, but specialized for  from  System.RandomA, so that you can serialize and resume. This is needed because  doesn't have a p instance.See the documentation of ? for more information on this .BLike @, but specialized for  from  System.RandomA, so that you can serialize and resume. This is needed because  doesn't have a p instance.See the documentation of @ for more information on this .C,The non-serializing/non-resuming version of ?.D,The non-serializing/non-resuming version of @.E Simulates a  .http://en.wikipedia.org/wiki/Bernoulli_processBernoulli ProcessR: a process of sequential independent trials each with a success of probability p.Implemented here is an z producing a blip stream that emits whenever the bernoulli process succeeds with the value of the received input of the 9, with its probability of succuss per each trial as the  parameter.%It is expected that, for probability p6, the stream will emit a value on average once every 1/p ticks.FLike E, but specialized for  from  System.RandomA, so that you can serialize and resume. This is needed because  doesn't have a p instance.See the documentation of E for more information on this .G,The non-serializing/non-resuming version of E.HE), but uses an underlying entropy source (C) to get its randomness from, instead of an initially passed seed.You can recover exactly E p by using M (H p).See M for more information.IAn Nq that is "on" and "off" for contiguous but random intervals of time...when "on", allows values to pass as "on" (>), but when "off", suppresses all incoming values (outputing ).You provide a , an l% parameter, representing the averageexpected length of each on off interval.0The distribution of interval lengths follows a  3http://en.wikipedia.org/wiki/Geometric_distributionGeometric Distributionj. This distribution is, as we call it in maths, "memoryless", which means that the "time left" that the P will be "on" or "off" at any given time is going to be, on average, the given l parameter.DInternally, the "toggling" events follow a bernoulli process with a p parameter of 1 / l.JLike I, but specialized for  from  System.RandomA, so that you can serialize and resume. This is needed because  doesn't have a p instance.See the documentation of I for more information on this .K,The non-serializing/non-resuming version of I.LI), but uses an underlying entropy source (C) to get its randomness from, instead of an initially passed seed.You can recover exactly I l by using M (L l).See M for more information.M Takes an  over an Rand or Q underlying monad as an entropy source, and "seals it away" to just be a normal  or : M ::  (Rand g) a b -> g ->  a b "You can now compose your entropic  with other  s (using 1, and other combinators) as if it were a normal .qUseful because you can create entire programs that have access to an underlying entropy souce by composing with Rand?...and then, at the end of it all, use/compose it with normal s as if it were a "pure" .N,The non-serializing/non-resuming version of Nz. The random seed is not re-loaded/resumed, so every time you resume, the stream of available randomness begins afresh.OLike M, but specialized for  from  System.RandomA, so that you can serialize and resume. This is needed because  doesn't have a p instance.See the documentation of M* for more information on this combinator.9random generating functionrandom generator seed:random generating functionrandom generator seed;random generating functionrandom generator seed<$(monadic) random generating functionrandom generator seed=$(monadic) random generating functionrandom generator seed>$(monadic) random generating functionrandom generator seed? random arrowrandom generator seed@(monadic) random arrowrandom generator seedA random arrowrandom generator seedB(mondic) random arrowrandom generator seedC random arrowrandom generator seedD(monadic) random arrowrandom generator seedE probability of any step emittingrandom generator seedF probability of any step emitting0random generator seed (between 0 and 1)G probability of any step emitting0random generator seed (between 0 and 1)H6probability of any step emiting (between 0 and 1)I#expected length of on/off intervalsrandom generator seedJ#expected length of on/off intervalsrandom generator seedK#expected length of on/off intervalsrandom generator seedL#expected length of on/off intervalsM to seal initial seedN to seal initial seedO to seal initial seed9:;<=>?@ABCDEFGHIJKLMNO9:;<=>?@ABCDEFGIJKMONHL9:;<=>?@ABCDEFGHIJKLMNOLCombinators for dynamically switching between and sequencing s.(c) Justin Le 2015MIT justin@jle.imunstableportableNone P*"This, then that". Behave like the first N: (and run its effects) as long as it is "on" (outputting !). As soon as it turns off (is ;), it'll "switch over" and begin behaving like the second , forever, running the effects of the second , too. Works well if the "s follow interval semantics from Control.Auto.Interval. let a1 = whenI (<= 4) --> pure 0streamAuto' a1 [1..10][1, 2, 3, 4, 0, 0, 0, 0, 0, 0](VY only lets items satisfying the predicate pass through as "on", and is "off" otherwise;  is the ' that always produces the same output)0Association works in a way that you can "chain" P's, as long as you have an appropriate  (and not N ) at the end:let a2 = onFor 3 . sumFrom 0" --> onFor 3 . sumFrom 100 --> pure 0streamAuto' a2 [1..10][1,3,6,104,109,115,0,0,0,0] a --> b --> c associates as a --> (b --> c)%This is pretty invaluable for having (s "step" through a series of different 8s, progressing their state from one stage to the next. Qs can control when they want to be "moved on" from by turning "off" (outputting ).0Note that recursive bindings work just fine, so:let a3 = onFor 2 . pure "hello"# --> onFor 2 . pure "world" --> a3"let (res3, _) = stepAutoN' 8 a3 ()res3H["hello", "hello", "world", "world", "hello", "hello", "world", "world"]Ythe above represents an infinite loop between outputting "hello" and outputting "world".EFor serialization, an extra byte cost is incurred per invocation of P. For cyclic switches like a3>, every time the cycle "completes", it adds another layer of P. byte costs. For example, initially, saving a3 incurs a cost for the two P s. After a3/ loops once, it incurs a cost for another two Ps, so it costs four P s. After a3. loops another time, it is like a cost of six P/s. So be aware that for cyclic bindings like a3), space for serialization grows at O(n).4By the way, it might be worth contrasting this with b and a from Control.Auto.IntervalM, which have the same type signatures. Those alternative-y operators always feed the input to both sides, run both sides, and output the first . With b0, you can "switch back and forth" to the first  as soon as the first  is "on" () again.P, in contrast, runs only the first  until it is off ()...then runs only the second (. This transition is one-way, as well.QA variation of P,, where the right hand side can also be an N / !. The entire result is, then, a . Probably less useful than P in most situations.RR n a1 a2 will behave like a1 for n( steps of output, and then behave like a2 forever after.HMore or less a more efficient/direct implementation of the common idiom: onFor n a1 --> a2 S Takes an g who has both a normal output stream and a blip stream output stream, where the blip stream emits new s.You can imagine S as a box containing a single F like the one just described. It feeds its input into the contained O, and its output stream is the "normal value" output stream of the contained .5However, as soon as the blip stream of the contained  emits a new , it replaces the contained  with the newZ one (just after emitting the "normal value"), and the whole thing starts all over again.S a0 will "start" with a0 already in the box.This is mostly useful to allow ]s to "replace themselves" or control their own destiny, or the behavior of their successors.In the following example, a1 is an V that behaves like a cumulative sum but also outputs a blip stream that will emit an  containing  100 (the + that always emits 100) after three steps. a1 :: Auto' Int (Int, Blip (Auto' Int Int)) a1 = proc x -> do sums <- sumFrom 0 -< x switchBlip <- inB 4 -< pure 100 id -< (sums, switchBlip) -- alternatively a1' = sumFrom 0 &&& (tagBlips (pure 100) . inB 4) So, S a1 will be the output of count& for three steps, and then switch to  100* afterwards (when the blip stream emits):$streamAuto' (switchFrom_ a1) [1..10]"[1,3,6,10,100,100,100,100,100,100]CThis is fun to use with recursion, so you can get looping switches: a2 :: Auto' Int (Int, Blip (Auto' Int Int)) a2 = proc x -> do sums <- sumFrom 0 -< x switchBlip <- inB 3 -< switchFrom_ a2 id -< (c, switchBlip) -- alternatively a2' = sumFrom 0 &&& (tagBlips (switchFrom_ a2') . inB 3) 'streamAuto' (switchFrom_ a2) [101..112]H[ 101, 203, 306 -- first 'sumFrom', on first three items [101, 102, 103]J, 104, 209, 315 -- second 'sumFrom', on second three items [104, 105, 106]H, 107, 215, 324 -- third 'sumFrom', on third three items [107, 108, 109]I, 110, 221, 333 -- final 'sumFrom', on fourth three items [110, 111, 112]]Note that this combinator is inherently unserializable, so you are going to lose all serialization capabilities if you use this. So sad, I know! :( This fact is reflected in the underscore suffix, as per convention.If you want to use switching andP have serialization, you can use the perfectly serialization-safe alternative, U, which slightly less powerful in ways that are unlikely to be missed in practical usage. That is, almost all non-contrived real life usages of S can be recovered using U.T:You can think of this as a little box containing a single d inside. Takes two input streams: an input stream of normal values, and a blip stream containing 2s. It feeds the input stream into the contained :...but every time the input blip stream emits with a new , replaces the contained T with the emitted one. Then starts the cycle all over, immediately giving the new  the received input./Useful for being able to externally "swap out" 0s for a given situation by just emitting a new  in the blip stream."For example, here we push several %s one after the other into the box: sumFrom 0,  productFrom 1, and count.  4 emits each < in the given list every four steps, starting on the fourth. newAutos :: Auto' Int (Blip (Auto' Int Int)) newAutos = eachAt_ 4 [sumFrom 0, productFrom 1, count] a :: Auto' Int Int a = proc i -> do blipAutos <- newAutos -< () switchOn_ (pure 0) -< (i, blipAutos) -- alternatively a' = switchOn_ (pure 0) . (id &&& newAutos) streamAuto' a [1..12]/[ 1, 3, 6 -- output from sumFrom 03, 4, 20, 120 -- output from productFrom 1+, 0, 1, 2, 3, 4, 5] -- output from countLike Sg, this combinator is inherently unserializable. So if you use it, you give up serialization for your 0s. This is reflected in the underscore suffix.TIf you wish to have the same switching devices but keep serialization, you can use XY, which is slightly less powerful, but should be sufficient for all practical use cases.UEssentially identical to S, except insead of the " outputting a blip stream of new 5s to replace itself with, it emits a blip stream of c --- and U uses the c to create the new .0Here is the equivalent of the two examples from S, implemented with U; see the documentation for S+ for a description of what they are to do. a1 :: Auto' Int (Int, Blip Int) a1 = proc x -> do sums <- sumFrom 0 -< x switchBlip <- inB 4 -< 100 id -< (sums, switchBlip) -- alternatively a1' = sumFrom 0 &&& (tagBlips 100 . inB 4) ;streamAuto' (switchFromF (\x -> (x,) <$> never) a1) [1..10]"[1,3,6,10,100,100,100,100,100,100] a2 :: Auto' Int (Int, Blip ()) a2 = proc x -> do sums <- sumFrom 0 -< x switchBlip <- inB 3 -< () id -< (sums, switchBlip) -- alternatively a2' = sumFrom 0 &&& (tagBlips () . inB 3) 2streamAuto' (switchFromF (const a2) a2) [101..112]I[ 101, 203, 306 -- first 'sumFrom', on first three items [101, 102, 103]K, 104, 209, 315 -- second 'sumFrom', on second three items [104, 105, 106]I, 107, 215, 324 -- third 'sumFrom', on third three items [107, 108, 109]J, 110, 221, 333] -- final 'sumFrom', on fourth three items [110, 111, 112]%Or, if you're only ever going to use a2 in switching form: a2s :: Auto' Int Int a2s = switchFromF (const a2s) $ proc x -> do sums <- sumFrom 0 -< x switchBlip <- inB 3 -< () id -< (c, swichBlip) -- or a2s' = switchFromF (const a2s') $ sumFrom 0 &&& (tagBlips () . inB 3) streamAuto' a2s [101..112]<[101, 203, 306, 104, 209, 315, 107, 215, 324, 110, 221, 333]0As you can see, all of the simple examples from S can be implemented in U?...and so can most real-life examples. The advantage is that U is serializable, and S is not.3Note that for the examples above, instead of using C, we could have actually used the input parameter to create a new  based on what we outputted.V,The non-serializing/non-resuming version of U". You sort of might as well use Sg; this version might give rise to more "disciplined" code, however, by being more restricted in power.W Gives an ) the ability to "reset" itself on commandBasically acts like j  :fmap fst :: Monad m => Auto m a (b, Blip c) -> Auto m a b 4But...whenever the blip stream emits..."resets" the : back to the original state, as if nothing ever happened.-Note that this resetting happens on the step after the blip stream emits.kHere is a summer that sends out a signal to reset itself whenever the cumulative sum reaches 10 or higher: ZlimitSummer :: Auto' Int (Int, Blip ()) limitSummer = (id &&& became (>= 10)) . sumFrom 0 And now we throw it into W: IresettingSummer :: Auto' Int Int resettingSummer = resetFrom limitSummer #streamAuto' resettingSummer [1..10] [ 1, 3, 6, 10 -- and...reset! , 5, 11 -- and...reset! , 7, 15 -- and...reset! , 9, 19 ]XEssentially identical to T4, except instead of taking in a blip stream of new /s to put into the box, takes a blip stream of c --- and X uses the c to create the new  to put in the box.0Here is the equivalent of the two examples from T, implemented with X; see the documentatino for T+ for a description of what they are to do. /newAuto :: Int -> Auto' Int Int newAuto 1 = sumFrom 0 newAuto 2 = productFrom 1 newAuto 3 = count newAuto _ = error "Do you expect rigorous error handling from a toy example?" a :: Auto' Int Int a = proc i -> do blipAutos <- eachAt 4 [1,2,3] -< () switchOnF_ newAuto (pure 0) -< (i, blipAutos) streamAuto' a [1..12]/[ 1, 3, 6 -- output from sumFrom 03, 4, 20, 120 -- output from productFrom 1+, 0, 1, 2, 3, 4, 5] -- output from count'Instead of sending in the "replacement C", sends in a number, which corresponds to a specific replacement .0As you can see, all of the simple examples from T can be implemented in X?...and so can most real-life examples. The advantage is that X is serializable, and T is not.Y,The non-serializing/non-resuming version of X!. You sort of might as well use Tg; this version might give rise to more "disciplined" code, however, by being more restricted in power.ZTakes an innocent K and wraps a "reset button" around it. It behaves just like the original ? at first, but when the input blip stream emits, the internal  is reset back to the beginning. Here we have sumFrom wrapped around a reset button, and we send in a blip stream that emits every 4 steps; so every 4th step, the whole summer resets..let a = resetOn (sumFrom 0) . (id &&& every 4)streamAuto' a [101..112][ 101, 203, 306, 104, 209, 315 -- resetted!, 107, 215, 324 -- resetted!, 110, 221, 333] -- resetted! Pinitial behavior7final behavior, when the initial behavior turns off.Qinitial behavior7final behavior, when the initial behavior turns off.R"number of outputs before switchinginitial behaviorswitched behaviorS outputting a normal output (b)) and a blip stream containing the  to replace itself with.Tinitial U!function to generate the next  to behave likeinitial . the b: is the output, and the blip stream triggers new s to replace this one.V!function to generate the next  to behave likeinitial . the b: is the output, and the blip stream triggers new s to replace this one.WThe self-resetting Xfunction to generate the next  to behave likeinitial starting  to behave likeYfunction to generate the next  to behave likeinitial starting  to behave likeZ to repeatedly reset PQRSTUVWXYZ PQRSTXYUVZW PQRSTUVWXYZP1Q1Main entry point to the auto library.(c) Justin Le 2015MIT justin@jle.imunstableportableNone^g}~|\     `n !"#$%&'()*+,-./]h0123456789:;<=>?@ABCDEFGHIJKL  #$%&'()*+,>MNOPQSeopqrwxyz{|} &PQK>NM  &%'&()+*, #$woqprxyz{|}PQ SeOPQM !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPOQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~        !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGH I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _`abcdefghijklmnopqrstuvwxyz{y|}~n~~~ryrr~n    ~w                  w   y   ! "~#$% & '()*+,lml-./0123455677899:;<<=>>?@ABCCDEFEGEHEIEJEKELEMEMENrOrPrQrRrSrTrUrVrWrXrYrYrZr[r\r]r^r_r`rarbrcrdrerenfnghihihjklklkmknknkokpkpkqkrkrksktktkukvkvkwxyz{|}~#auto-0.4.3.1-HNJqqybobBbJ06ezEJkkhZControl.Auto.Generate Control.AutoControl.Auto.CoreControl.Auto.EffectsControl.Auto.SerializeControl.Auto.BlipControl.Auto.Blip.InternalControl.Auto.IntervalControl.Auto.ProcessControl.Auto.RunControl.Auto.TimeControl.Auto.CollectionControl.Auto.Process.RandomControl.Auto.SwitchbaseGHC.BasepureAuto'AutotoArb autoConstrhoistA generalizeA forceSerial encodeAuto decodeAuto resumeAutosaveAuto unserializestepAuto stepAuto' purifyAutoevalAuto evalAuto'execAuto execAuto'forcerseqer interceptOmkAutomkAutoMmkAuto_mkAutoM_mkConstmkConstMmkFuncmkFuncMmkStatemkStateMmkState' mkStateM'mkState_ mkStateM_accumaccumMaccum_accumM_accumDaccumMDaccumD_accumMD_$fFloatingAuto$fFractionalAuto $fNumAuto$fIsStringAuto $fMonoidAuto$fSemigroupAuto$fArrowLoopAuto$fArrowChoiceAuto $fArrowAuto$fCostrongAuto $fChoiceAuto $fStrongAuto$fProfunctorAuto$fCategoryTYPEAuto$fAlternativeAuto$fApplicativeAuto $fFunctorAutoBlipNoBlipmergemerge'mergeLmergeRblip $fNFDataBlip$fSerializeBlip $fMonoidBlip$fSemigroupBlip $fFunctorBlip $fShowBlip $fGenericBlip Interval'IntervalofftoOn fromIntervalfromIntervalWithonForoffForwindowwhenIunlessIafterbeforebetweenholdhold_holdForholdFor_ holdJusts holdJusts_<|?><|!>chooseIntervalchooseduringbindIcompIfromList fromLongList fromList_unfoldunfoldMunfold_unfoldM_iterator iteratorM iterator_ iteratorM_ enumFromA enumFromA_ discreteF discreteF_effectsumFromsumFrom_sumFromD sumFromD_ productFrom productFrom_deltasdeltas_ mappender mappender_ mappendFrom mappendFrom_ movingAveragemovingAverage_impulseResponseimpulseResponse_autoRegressionautoRegression_armaarma_overListoverTraversable overList'overTraversable' streamAuto streamAuto' stepAutoN stepAutoN' evalAutoN evalAutoN'throughTrunrunM interactAuto interactRS interactM duringReadbindRead runOnChanM runOnChantoEffectStreamstreamAutoEffectsreadAuto readAutoDef writeAutosavingloadingloading' serializing serializing' saveFromB loadFromB loadFromB'saveOnBloadOnBloadOnB'countcount_lastVallastVal_arrDarrD_delaydelay_ delayList delayList_delayNdelayN_stretchstretch_stretchAccumBystretchAccumBy_stretchB accelOverList accelerateaccelerateWithskipTo fastForwardfastForwardEitherprimingzipAutodZipAuto dZipAuto_zipAutoB dZipAutoB dZipAutoB_dynZip_dynZipFdynZipF_dynMap_dynMapFdynMapF_muxmux_muxManymuxMany_muxImuxI_muxManyI muxManyI_gathergather_gather__ gatherMany gatherMany_ gatherMany__mergeLsmergeRsfoldrBfoldlB'<&&>never immediatelyinBcollectN collectN_ collectBs collectBs_emitOn emitJustseveryeachAteachAt_filterBsplitB splitEitherBjoinBcollectB collectB_ mapMaybeBoncenotYettakeB takeWhileBdropB dropWhileBlagBlips lagBlips_accumBaccumB_scanBscanB_mscanBmscanB_countBbecamenoLongeronFlipbecame_ noLonger_onFlip_became' noLonger'onFlip'onChange onChange_onJusts onEithers emitEithers fromBlips fromBlipsWithasMaybes substituteBholdWith holdWith_tagBlips modifyBlipsperBlipcachecache_execOnce execOnce_effectsarrMarrMBeffectBexecB runReaderA sealReader sealReader_ sealReaderMsealReaderMVarreaderA runWriterAwriterA sealState sealState_ runStateAstateAaccumArunTraversableAcatchArandsstdRandsrands_randsM stdRandsMrandsM_arrRandarrRandM arrRandStd arrRandStdMarrRand_ arrRandM_ bernoulli stdBernoulli bernoulli_ bernoulliMR randIntervalsstdRandIntervalsrandIntervals_randIntervalsMR sealRandom sealRandom_ sealRandomStd-->-?>switchIn switchFrom_ switchOn_ switchFromF switchFromF_ resetFrom switchOnF switchOnF_resetOnMonadData.Functor.IdentityIdentityControl.CategoryCategory ApplicativeFunctor Control.ArrowArrowbytestring-0.10.8.1Data.ByteString.Internal ByteString Data.EitherLeft%cereal-0.5.4.0-LXuGw964IxKFJaPTyZmzLsData.Serialize.GetGetData.Serialize.PutPutghc-prim GHC.TypesInt System.IOputStrLn*>idGHC.PrimseqfmapFalseTrueData.TraversablemapMarr mapAccumLData.Serialize Serialize Data.FoldablefoldlGHC.Listscanl Control.MonadfoldMGHC.Err undefinedGHC.Realrecip fromRationalRationalGHC.NumNumnegate fromInteger integer-gmpGHC.Integer.TypeIntegermemptyData.Semigroup<>Monoid ArrowLoop ArrowChoice&profunctors-5.2-95z199kZ1wT5n9vMdHluoaData.Profunctor.Unsafelmaprmap Profunctor Alternative<*>liftA2printIOAutoFunc AutoFuncM AutoState AutoStateMAutoArbAutoArbM mergeStStfirstMsecondMconstflip Data.MaybemaybeJustNothingMaybe fromMaybe. _holdForFiterateGHC.Enumsucc_uncons_unfoldF _unfoldMFmconcatmappend Semigrouprepeat_deltasF_movingAverageF_autoRegressionF_armaF Traversabletransformers-0.5.2.0 Control.Monad.Trans.State.StrictmodifyStringGHC.Showshow Text.ReadreadGHC.ReadReadShowBoolControl.Concurrent.ChanChanGHC.IOFilePathRight readAutoErrControl.Monad.IO.ClassMonadIO<$+ stretchBy stretchBy_iterateMcontainers-0.5.7.1Data.IntMap.BaseIntMap Data.Map.BaseMapMapMerge_dynZipF_dynMapF _muxManyF _muxManyIFe2m_muxgathermapF gatherFMany gatherFMany__loadAs gatherFMany__ _gatherFManyFgenericZipMapWithDefaultszipIntMapWithDefaults_zipMapWithDefaultsEither _collectBsF_eachAtF _collectBF_accumBF_scanBF_becameF _onChangeFControl.Monad.Trans.ReaderReaderTgetgetLineGHC.MVarMVarControl.Monad.Trans.Writer.LazyWriterTControl.Monad.Trans.State.LazyStateTdiv GHC.Exception Exception_cacheF _execOnceF!random-1.1-54KmMHXjttlERYcr1mvsAe System.Randomrandom RandomGenrandomRStdGen&MonadRandom-0.5-InYiOZYIbHv2TCJHvMGquiControl.Monad.Trans.Random.LazyrunRandTRandTDoubleControl.Monad.Random.Class MonadRandom _bernoulliF_randIntervalsF Data.Tuplefst<*sconcatstimes runIdentitydiffoption mtimesDefaultstimesIdempotentstimesIdempotentMonoid stimesMonoidcycle1MingetMinMaxgetMaxArgArgMinArgMaxFirstgetFirstLastgetLast WrappedMonoid WrapMonoid unwrapMonoidOption getOptionControl.Applicativeoptional WrappedMonad WrapMonad unwrapMonad WrappedArrow WrapArrow unwrapArrowZipList getZipListleftApp^<<<<^>>^^>>returnAfirstsecond***&&&Kleisli runKleisli ArrowZero zeroArrow ArrowPlus<+>|||+++leftright ArrowApplyapp ArrowMonad>>><<<Data.Functor.ConstConstgetConst Data.MonoidDualgetDualEndoappEndoAllgetAllAnygetAnySumgetSumProduct getProduct Data.Functor<$>liftA3liftA<**>empty<|>somemany