-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/

-- | Library for functional reactive programming (FRP).
--   
--   Reactive-banana is a library for Functional Reactive Programming
--   (FRP).
--   
--   FRP offers an elegant and concise way to express interactive programs
--   such as graphical user interfaces, animations, computer music or robot
--   controllers. It promises to avoid the spaghetti code that is all too
--   common in traditional approaches to GUI programming.
--   
--   See the project homepage
--   http://wiki.haskell.org/Reactive-banana for more detailed
--   documentation and examples.
--   
--   Stability forecast. This is a stable library, though minor API
--   changes are still likely. It features an efficient, push-driven
--   implementation and has seen some optimization work.
--   
--   API guide. Start with the Reactive.Banana module.
@package reactive-banana
@version 1.3.2.0

module Control.Event.Handler

-- | An event handler is a function that takes an event value
--   and performs some computation.
type Handler a = a -> IO ()

-- | The type AddHandler represents a facility for registering event
--   handlers. These will be called whenever the event occurs.
--   
--   When registering an event handler, you will also be given an action
--   that unregisters this handler again.
--   
--   
--   do unregisterMyHandler <- register addHandler myHandler
--   
newtype AddHandler a
AddHandler :: (Handler a -> IO (IO ())) -> AddHandler a
[register] :: AddHandler a -> Handler a -> IO (IO ())

-- | Build a facility to register and unregister event handlers. Also
--   yields a function that takes an event handler and runs all the
--   registered handlers.
--   
--   Example:
--   
--   
--   do
--       (addHandler, fire) <- newAddHandler
--       register addHandler putStrLn
--       fire "Hello!"
--   
newAddHandler :: IO (AddHandler a, Handler a)

-- | Map the event value with an IO action.
mapIO :: (a -> IO b) -> AddHandler a -> AddHandler b

-- | Filter event values that don't return True.
filterIO :: (a -> IO Bool) -> AddHandler a -> AddHandler a
instance GHC.Internal.Base.Functor Control.Event.Handler.AddHandler
instance GHC.Internal.Base.Monoid (Control.Event.Handler.Callback a)
instance GHC.Internal.Base.Semigroup (Control.Event.Handler.Callback a)

module Reactive.Banana.Model

-- | Natural numbers (poorly represented).
type Nat = Int

-- | The FRP model used in this library is actually a model with continuous
--   time.
--   
--   However, it can be shown that this model is observationally equivalent
--   to a particular model with (seemingly) discrete time steps, which is
--   implemented here. The main reason for doing this is to be able to
--   handle recursion correctly. Details will be explained elsewhere.
type Time = Nat

-- | Event is modeled by an infinite list of Maybe values. It
--   is isomorphic to Time -> Maybe a.
--   
--   Nothing indicates that no occurrence happens, while Just
--   indicates that an occurrence happens.
newtype Event a
E :: [Maybe a] -> Event a
[unE] :: Event a -> [Maybe a]

-- | Behavior is modeled by an infinite list of values. It is
--   isomorphic to Time -> a.
newtype Behavior a
B :: [a] -> Behavior a
[unB] :: Behavior a -> [a]
interpret :: (Event a -> Moment (Event b)) -> [Maybe a] -> [Maybe b]
never :: Event a
unionWith :: (a -> a -> a) -> Event a -> Event a -> Event a
mergeWith :: (a -> c) -> (b -> c) -> (a -> b -> c) -> Event a -> Event b -> Event c
filterJust :: Event (Maybe a) -> Event a
apply :: Behavior (a -> b) -> Event a -> Event b
newtype Moment a
M :: (Time -> a) -> Moment a
[unM] :: Moment a -> Time -> a
accumE :: a -> Event (a -> a) -> Moment (Event a)
stepper :: a -> Event a -> Moment (Behavior a)
valueB :: Behavior a -> Moment a
observeE :: Event (Moment a) -> Event a
switchE :: Event a -> Event (Event a) -> Moment (Event a)
switchB :: Behavior a -> Event (Behavior a) -> Moment (Behavior a)
instance GHC.Internal.Base.Applicative Reactive.Banana.Model.Behavior
instance GHC.Internal.Base.Applicative Reactive.Banana.Model.Moment
instance GHC.Internal.Base.Functor Reactive.Banana.Model.Behavior
instance GHC.Internal.Base.Functor Reactive.Banana.Model.Event
instance GHC.Internal.Base.Functor Reactive.Banana.Model.Moment
instance GHC.Internal.Control.Monad.Fix.MonadFix Reactive.Banana.Model.Moment
instance GHC.Internal.Base.Monad Reactive.Banana.Model.Moment
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Reactive.Banana.Model.Behavior a)
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Reactive.Banana.Model.Event a)

module Reactive.Banana.Prim.High.Cached
data Cached (m :: Type -> Type) a
runCached :: Cached m a -> m a

-- | An action whose result will be cached. Executing the action the first
--   time in the monad will execute the side effects. From then on, only
--   the generated value will be returned.
cache :: (MonadFix m, MonadIO m) => m a -> Cached m a

-- | Return a pure value. Doesn't make use of the cache.
fromPure :: forall (m :: Type -> Type) a. Monad m => a -> Cached m a

-- | Lift an action that is not cached, for instance because it is
--   idempotent.
don'tCache :: Monad m => m a -> Cached m a
liftCached1 :: (MonadFix m, MonadIO m) => (a -> m b) -> Cached m a -> Cached m b
liftCached2 :: (MonadFix m, MonadIO m) => (a -> b -> m c) -> Cached m a -> Cached m b -> Cached m c

module Reactive.Banana.Prim.Low.Graph

-- | A directed graph whose set of vertices is the set of all values of the
--   type v and whose edges are associated with data of type
--   e.
--   
--   Note that a Graph does not have a notion of vertex membership —
--   by design, all values of the type v are vertices of
--   the Graph. The main purpose of Graph is to keep track of
--   directed edges between vertices; a vertex with at least one edge
--   incident on it is called a connected vertex. For efficiency,
--   only the connected vertices are stored.
data Graph v e

-- | The graph with no edges.
empty :: Graph v e

-- | Get all direct successors of a vertex in a Graph.
getOutgoing :: (Eq v, Hashable v) => Graph v e -> v -> [(e, v)]

-- | Get all direct predecessors of a vertex in a Graph.
getIncoming :: (Eq v, Hashable v) => Graph v e -> v -> [(v, e)]

-- | Number of connected vertices, i.e. vertices on which at least one edge
--   is incident.
size :: (Eq v, Hashable v) => Graph v e -> Int

-- | Number of edges.
edgeCount :: (Eq v, Hashable v) => Graph v e -> Int

-- | List all connected vertices, i.e. vertices on which at least one edge
--   is incident.
listConnectedVertices :: (Eq v, Hashable v) => Graph v e -> [v]

-- | Remove all edges incident on this vertex from the Graph.
deleteVertex :: (Eq v, Hashable v) => v -> Graph v e -> Graph v e

-- | Insert an edge from the first to the second vertex into the
--   Graph.
insertEdge :: (Eq v, Hashable v) => (v, v) -> e -> Graph v e -> Graph v e

-- | TODO: Not implemented.
deleteEdge :: (Eq v, Hashable v) => (v, v) -> Graph v e -> Graph v e

-- | Remove all the edges that connect the given vertex to its
--   predecessors.
clearPredecessors :: (Eq v, Hashable v) => v -> Graph v e -> Graph v e

-- | Apply deleteVertex to all vertices which are not predecessors
--   of any of the vertices in the given list.
collectGarbage :: (Eq v, Hashable v) => [v] -> Graph v e -> Graph v e

-- | If the Graph is acyclic, return a topological sort, that is a
--   linear ordering of its connected vertices such that each vertex occurs
--   before its successors.
--   
--   (Vertices that are not connected are not listed in the topological
--   sort.)
--   
--   https://en.wikipedia.org/wiki/Topological_sorting
topologicalSort :: (Eq v, Hashable v) => Graph v e -> [v]
data Step
Next :: Step
Stop :: Step

-- | Starting from a list of vertices without predecessors, walk through
--   all successors, but in such a way that every vertex is visited before
--   its predecessors. For every vertex, if the function returns
--   Next, then the successors are visited, otherwise the walk at
--   the vertex stops prematurely.
--   
--   
--   topologicalSort g =
--       runIdentity $ walkSuccessors (roots g) (pure Next) g
--   
walkSuccessors :: forall v e m. (Monad m, Eq v, Hashable v) => [v] -> (v -> m Step) -> Graph v e -> m [v]
walkSuccessors_ :: (Monad m, Eq v, Hashable v) => [v] -> (v -> m Step) -> Graph v e -> m ()

-- | Levels are used to keep track of the order of vertices — Lower
--   levels come first.
type Level = Int

-- | Get the Level of a vertex in a Graph.
getLevel :: (Eq v, Hashable v) => Graph v e -> v -> Level

-- | Map to a string in graphviz dot file format.
showDot :: (Eq v, Hashable v) => (v -> String) -> Graph v e -> String
instance (GHC.Classes.Eq v, GHC.Classes.Eq e) => GHC.Classes.Eq (Reactive.Banana.Prim.Low.Graph.Graph v e)
instance (GHC.Internal.Show.Show v, GHC.Internal.Show.Show e) => GHC.Internal.Show.Show (Reactive.Banana.Prim.Low.Graph.Graph v e)

module Reactive.Banana.Prim.Low.Ref

-- | A mutable reference which has a Unique associated with it.
data Ref a
getUnique :: Ref a -> Unique
new :: MonadIO m => a -> m (Ref a)
equal :: Ref a -> Ref b -> Bool
read :: MonadIO m => Ref a -> m a
put :: MonadIO m => Ref a -> a -> m ()

-- | Strictly modify a Ref.
modify' :: MonadIO m => Ref a -> (a -> a) -> m ()

-- | Add a finalizer to a Ref.
--   
--   See addFinalizer.
addFinalizer :: Ref v -> IO () -> IO ()
getWeakRef :: Ref a -> WeakRef a

-- | Weak pointer to a Ref.
type WeakRef v = Weak Ref v

-- | Create a weak pointer that associates a key with a value.
--   
--   See mkWeak.
mkWeak :: Ref k -> v -> Maybe (IO ()) -> IO (Weak v)

-- | Dereference a WeakRef.
--   
--   See deRefWeak.
deRefWeak :: Weak v -> IO (Maybe v)

-- | Dereference a list of weak pointers while discarding dead ones.
deRefWeaks :: [Weak v] -> IO [v]

-- | Finalize a WeakRef.
--   
--   See finalize.
finalize :: WeakRef v -> IO ()
instance GHC.Classes.Eq (Reactive.Banana.Prim.Low.Ref.Ref a)
instance Data.Hashable.Class.Hashable (Reactive.Banana.Prim.Low.Ref.Ref a)
instance Control.DeepSeq.NFData (Reactive.Banana.Prim.Low.Ref.Ref a)

module Reactive.Banana.Prim.Low.GraphGC

-- | A directed graph whose edges are mutable and whose vertices are
--   subject to garbage collection.
--   
--   The vertices of the graph are mutable references of type 'Ref v'.
--   
--   Generally, the vertices of the graph are not necessarily kept
--   reachable by the GraphGC data structure — they need to be kept
--   reachable by other parts of your program.
--   
--   That said, the edges in the graph do introduce additional reachability
--   between vertices: Specifically, when an edge (x,y) is present in the
--   graph, then the head y will keep the tail x
--   reachable. (But the liveness of y needs to come from
--   elsewhere, e.g. another edge.) Use insertEdge to insert an
--   edge.
--   
--   Moreover, when a vertex is removed because it is no longer reachable,
--   then all edges to and from that vertex will also be removed. In turn,
--   this may cause further vertices and edges to be removed.
--   
--   Concerning garbage collection: Note that vertices and edges will not
--   be removed automatically when the Haskell garbage collector runs —
--   they will be marked as garbage by the Haskell runtime, but the actual
--   removal of garbage needs to be done explicitly by calling
--   removeGarbage. This procedure makes it easier to reason about
--   the state of the GraphGC during a call to e.g.
--   walkSuccessors.
data GraphGC v

-- | List all vertices that are reachable and have at least one edge
--   incident on them. TODO: Is that really what the function does?
listReachableVertices :: GraphGC v -> IO [Ref v]
getSize :: GraphGC v -> IO Int

-- | Create a new GraphGC.
new :: IO (GraphGC v)

-- | Insert an edge from the first vertex to the second vertex.
insertEdge :: (Ref v, Ref v) -> GraphGC v -> IO ()

-- | Remove all the edges that connect the vertex to its predecessors.
clearPredecessors :: Ref v -> GraphGC v -> IO ()
data Step
Next :: Step
Stop :: Step

-- | Walk through all successors. See walkSuccessors.
walkSuccessors :: Monad m => [Ref v] -> (WeakRef v -> m Step) -> GraphGC v -> IO (m [WeakRef v])

-- | Walk through all successors. See walkSuccessors_.
walkSuccessors_ :: Monad m => [Ref v] -> (WeakRef v -> m Step) -> GraphGC v -> IO (m ())

-- | Explicitly remove all vertices and edges that have been marked as
--   garbage by the Haskell garbage collector.
removeGarbage :: GraphGC v -> IO ()

-- | Show the underlying graph in graphviz dot file format.
printDot :: (Unique -> WeakRef v -> IO String) -> GraphGC v -> IO String

module Reactive.Banana.Prim.Mid
type Step = EvalNetwork IO ()
type EvalNetwork a = Network -> IO (a, Network)

-- | A Network represents the state of a pulse/latch network,
data Network
emptyNetwork :: IO Network
getSize :: Network -> IO Int
type Build = ReaderWriterIOT BuildR BuildW IO
liftIOLater :: IO () -> Build ()
type BuildIO = Build
liftBuild :: Build a -> BuildIO a
buildLater :: Build () -> Build ()

-- | Pretend to return a value right now, but do not actually calculate it
--   until later.
--   
--   NOTE: Accessing the value before it's written leads to an error.
--   
--   FIXME: Is there a way to have the value calculate on demand?
buildLaterReadNow :: Build a -> Build a

-- | Change a Network of pulses and latches by executing a
--   BuildIO action.
compile :: BuildIO a -> Network -> IO (a, Network)

-- | Simple interpreter for pulse/latch networks.
--   
--   Mainly useful for testing functionality
--   
--   Note: The result is not computed lazily, for similar reasons that the
--   sequence function does not compute its result lazily.
interpret :: (Pulse a -> BuildIO (Pulse b)) -> [Maybe a] -> IO [Maybe b]

-- | mapAccum for a monad.
mapAccumM :: Monad m => (a -> s -> m (b, s)) -> s -> [a] -> m ([b], s)

-- | Strict mapAccum for a monad. Discards results.
mapAccumM_ :: Monad m => (a -> s -> m (b, s)) -> s -> [a] -> m ()

-- | Execute an FRP network with a sequence of inputs. Make sure that
--   outputs are evaluated, but don't display their values.
--   
--   Mainly useful for testing whether there are space leaks.
runSpaceProfile :: Show b => (Pulse a -> BuildIO (Pulse b)) -> [a] -> IO ()

-- | Create a new pulse in the network and a function to trigger it.
--   
--   Together with addHandler, this function can be used to operate
--   with pulses as with standard callback-based events.
newInput :: Build (Pulse a, a -> Step)

-- | Register a handler to be executed whenever a pulse occurs.
--   
--   The pulse may refer to future latch values.
addHandler :: Pulse (Future a) -> (a -> IO ()) -> Build ()

-- | Read the value of a Latch at a particular moment in time.
readLatch :: Latch a -> Build a
data Pulse a

-- | Pulse that never fires.
neverP :: Build (Pulse a)
alwaysP :: Build (Pulse ())
mapP :: (a -> b) -> Pulse a -> Build (Pulse b)
type Future = IO

-- | Tag a Pulse with future values of a Latch.
--   
--   This is in contrast to applyP which applies the current value
--   of a Latch to a pulse.
tagFuture :: Latch a -> Pulse b -> Build (Pulse (Future a))
unsafeMapIOP :: (a -> IO b) -> Pulse a -> Build (Pulse b)
filterJustP :: Pulse (Maybe a) -> Build (Pulse a)
mergeWithP :: (a -> Maybe c) -> (b -> Maybe c) -> (a -> b -> Maybe c) -> Pulse a -> Pulse b -> Build (Pulse c)
type Latch a = Ref LatchD a
pureL :: a -> Latch a
mapL :: (a -> b) -> Latch a -> Latch b
applyL :: Latch (a -> b) -> Latch a -> Latch b
accumL :: a -> Pulse (a -> a) -> Build (Latch a, Pulse a)
applyP :: Latch (a -> b) -> Pulse a -> Build (Pulse b)
switchL :: Latch a -> Pulse (Latch a) -> Build (Latch a)
executeP :: forall a b. Pulse (b -> Build a) -> b -> Build (Pulse a)
switchP :: Pulse a -> Pulse (Pulse a) -> Build (Pulse a)

-- | Show the graph of the Network in graphviz dot file
--   format.
printDot :: Network -> IO String

module Reactive.Banana.Combinators

-- | Event a represents a stream of events as they occur in time.
--   Semantically, you can think of Event a as an infinite list of
--   values that are tagged with their corresponding time of occurrence,
--   
--   
--   type Event a = [(Time,a)]
--   
--   
--   Each pair is called an event occurrence. Note that within a
--   single event stream, no two event occurrences may happen at the same
--   time.
--   
data Event a

-- | Behavior a represents a value that varies in time.
--   Semantically, you can think of it as a function
--   
--   
--   type Behavior a = Time -> a
--   
--   
data Behavior a

-- | Interpret an event processing function. Useful for testing.
--   
--   Note: You can safely assume that this function is pure, even though
--   the type seems to suggest otherwise. I'm really sorry about the extra
--   IO, but it can't be helped. See source code for the sordid
--   details.
interpret :: (Event a -> Moment (Event b)) -> [Maybe a] -> IO [Maybe b]

-- | Event that never occurs. Semantically,
--   
--   
--   never = []
--   
never :: Event a

-- | Merge two event streams of the same type. The function argument
--   specifies how event values are to be combined in case of a
--   simultaneous occurrence. The semantics are
--   
--   
--   unionWith f ((timex,x):xs) ((timey,y):ys)
--      | timex <  timey = (timex,x)     : unionWith f xs ((timey,y):ys)
--      | timex >  timey = (timey,y)     : unionWith f ((timex,x):xs) ys
--      | timex == timey = (timex,f x y) : unionWith f xs ys
--   
unionWith :: (a -> a -> a) -> Event a -> Event a -> Event a

-- | Allow all events that fulfill the predicate, discard the rest.
--   Semantically,
--   
--   
--   filterE p es = [(time,a) | (time,a) <- es, p a]
--   
filterE :: (a -> Bool) -> Event a -> Event a

-- | Apply a time-varying function to a stream of events. Semantically,
--   
--   
--   apply bf ex = [(time, bf time x) | (time, x) <- ex]
--   
--   
--   This function is generally used in its infix variant <@>.
apply :: Behavior (a -> b) -> Event a -> Event b

-- | The Moment monad denotes a pure computation that happens
--   at one particular moment in time. Semantically, it is a reader monad
--   
--   
--   type Moment a = Time -> a
--   
--   
--   When run, the argument tells the time at which this computation
--   happens.
--   
--   Note that in this context, time really means to logical
--   time. Of course, every calculation on a computer takes some amount
--   of wall-clock time to complete. Instead, what is meant here is the
--   time as it relates to Events and Behaviors. We use the
--   fiction that every calculation within the Moment monad takes
--   zero logical time to perform.
data Moment a

-- | An instance of the MonadMoment class denotes a computation that
--   happens at one particular moment in time. Unlike the Moment
--   monad, it need not be pure anymore.
class MonadFix m => MonadMoment (m :: Type -> Type)
liftMoment :: MonadMoment m => Moment a -> m a

-- | The accumE function accumulates a stream of event values,
--   similar to a strict left scan, scanl'. It starts with
--   an initial value and emits a new value whenever an event occurrence
--   happens. The new value is calculated by applying the function in the
--   event to the old value.
--   
--   Example:
--   
--   
--   accumE "x" [(time1,(++"y")),(time2,(++"z"))]
--       = trimE [(time1,"xy"),(time2,"xyz")]
--       where
--       trimE e start = [(time,x) | (time,x) <- e, start <= time]
--   
accumE :: MonadMoment m => a -> Event (a -> a) -> m (Event a)

-- | Construct a time-varying function from an initial value and a stream
--   of new values. The result will be a step function. Semantically,
--   
--   
--   stepper x0 ex = \time1 -> \time2 ->
--       last (x0 : [x | (timex,x) <- ex, time1 <= timex, timex < time2])
--   
--   
--   Here is an illustration of the result Behavior at a particular time:
--   
--   
--   Note: The smaller-than-sign in the comparison timex <
--   time2 means that at time time2 == timex, the value of
--   the Behavior will still be the previous value. In the illustration,
--   this is indicated by the dots at the end of each step. This allows for
--   recursive definitions. See the discussion below for more on recursion.
stepper :: MonadMoment m => a -> Event a -> m (Behavior a)

-- | Obtain the value of the Behavior at a given moment in time.
--   Semantically, it corresponds to
--   
--   
--   valueB b = \time -> b time
--   
--   
--   Note: The value is immediately available for pattern matching.
--   Unfortunately, this means that valueB is unsuitable for use
--   with value recursion in the Moment monad. If you need
--   recursion, please use valueBLater instead.
valueB :: MonadMoment m => Behavior a -> m a

-- | Obtain the value of the Behavior at a given moment in time.
--   Semantically, it corresponds to
--   
--   
--   valueBLater b = \time -> b time
--   
--   
--   Note: To allow for more recursion, the value is returned lazily
--   and not available for pattern matching immediately. It can be used
--   safely with most combinators like stepper. If that doesn't work
--   for you, please use valueB instead.
valueBLater :: MonadMoment m => Behavior a -> m a

-- | Observe a value at those moments in time where event occurrences
--   happen. Semantically,
--   
--   
--   observeE e = [(time, m time) | (time, m) <- e]
--   
observeE :: Event (Moment a) -> Event a

-- | Dynamically switch between Event. Semantically,
--   
--   
--   switchE e0 ee0 time0 =
--       concat [ trim t1 t2 e | (t1,t2,e) <- intervals ee ]
--     where
--       laterThan e time0  = [(timex,x) | (timex,x) <- e, time0 < timex ]
--       ee                 = [(time0, e0)] ++ (ee0 `laterThan` time0)
--       intervals ee       = [(time1, time2, e) | ((time1,e),(time2,_)) <- zip ee (tail ee)]
--       trim time1 time2 e = [x | (timex,x) <- e, time1 < timex, timex <= time2]
--   
switchE :: MonadMoment m => Event a -> Event (Event a) -> m (Event a)

-- | Dynamically switch between Behavior. Semantically,
--   
--   
--   switchB b0 eb = \time0 -> \time1 ->
--      last (b0 : [b | (timeb,b) <- eb, time0 <= timeb, timeb < time1]) time1
--   
switchB :: MonadMoment m => Behavior a -> Event (Behavior a) -> m (Behavior a)

-- | Infix synonym for the apply combinator. Similar to
--   <*>.
--   
--   
--   infixl 4 <@>
--   
(<@>) :: Behavior (a -> b) -> Event a -> Event b
infixl 4 <@>

-- | Tag all event occurrences with a time-varying value. Similar to
--   <*.
--   
--   
--   infixl 4 <@
--   
(<@) :: Behavior b -> Event a -> Event b
infixl 4 <@

-- | Tag all event occurences with a time-varying value. Similar to
--   *>.
--   
--   This is the flipped version of <@, but can be useful when
--   combined with ApplicativeDo to sample from multiple
--   Behaviors:
--   
--   
--   reactimate $ onEvent @> do
--     x <- behavior1
--     y <- behavior2
--     return (print (x + y))
--   
(@>) :: Event a -> Behavior b -> Event b
infixl 4 @>

-- | Allow all event occurrences that are Just values, discard the
--   rest. Variant of filterE.
filterJust :: Event (Maybe a) -> Event a

-- | Allow all events that fulfill the time-varying predicate, discard the
--   rest. Generalization of filterE.
filterApply :: Behavior (a -> Bool) -> Event a -> Event a

-- | Allow events only when the behavior is True. Variant of
--   filterApply.
whenE :: Behavior Bool -> Event a -> Event a

-- | Split event occurrences according to a tag. The Left values go
--   into the left component while the Right values go into the
--   right component of the result.
split :: Event (Either a b) -> (Event a, Event b)

-- | Keep only the next occurence of an event.
--   
--   once also aids the garbage collector by indicating that the
--   result event can be discarded after its only occurrence.
--   
--   
--   once e = \time0 -> take 1 [(t, a) | (t, a) <- e, time0 <= t]
--   
once :: MonadMoment m => Event a -> m (Event a)

-- | Merge event streams whose values are functions. In case of
--   simultaneous occurrences, the functions at the beginning of the list
--   are applied after the functions at the end.
--   
--   
--   unions [] = never
--   unions xs = foldr1 (unionWith (.)) xs
--   
--   
--   Very useful in conjunction with accumulation functions like
--   accumB and accumE.
unions :: [Event (a -> a)] -> Event (a -> a)

-- | The accumB function accumulates event occurrences into a
--   Behavior.
--   
--   The value is accumulated using accumE and converted into a
--   time-varying value using stepper.
--   
--   Example:
--   
--   
--   accumB "x" [(time1,(++"y")),(time2,(++"z"))]
--      = stepper "x" [(time1,"xy"),(time2,"xyz")]
--   
--   
--   Note: As with stepper, the value of the behavior changes
--   "slightly after" the events occur. This allows for recursive
--   definitions.
accumB :: MonadMoment m => a -> Event (a -> a) -> m (Behavior a)

-- | Efficient combination of accumE and accumB.
mapAccum :: MonadMoment m => acc -> Event (acc -> (x, acc)) -> m (Event x, Behavior acc)

-- | Merge two event streams of any type.
merge :: Event a -> Event b -> Event (These a b)

-- | Merge two event streams of any type.
--   
--   This function generalizes unionWith.
mergeWith :: (a -> c) -> (b -> c) -> (a -> b -> c) -> Event a -> Event b -> Event c

module Reactive.Banana.Frameworks

-- | Simple way to write a single event handler with functional reactive
--   programming.
interpretAsHandler :: (Event a -> Moment (Event b)) -> AddHandler a -> AddHandler b

-- | Compile the description of an event network into an
--   EventNetwork that you can actuate, pause and so
--   on.
compile :: MomentIO () -> IO EventNetwork

-- | The MomentIO monad is used to add inputs and outputs to an
--   event network.
data MomentIO a

-- | Input, obtain an Event from an AddHandler.
--   
--   When the event network is actuated, this will register a callback
--   function such that an event will occur whenever the callback function
--   is called.
fromAddHandler :: AddHandler a -> MomentIO (Event a)

-- | Input, obtain a Behavior from an AddHandler that
--   notifies changes.
--   
--   This is essentially just an application of the stepper
--   combinator.
fromChanges :: a -> AddHandler a -> MomentIO (Behavior a)

-- | Input, obtain a Behavior by frequently polling mutable data,
--   like the current time.
--   
--   The resulting Behavior will be updated on whenever the event
--   network processes an input event.
--   
--   This function is occasionally useful, but the recommended way to
--   obtain Behaviors is by using fromChanges.
--   
--   Ideally, the argument IO action just polls a mutable variable, it
--   should not perform expensive computations. Neither should its side
--   effects affect the event network significantly.
fromPoll :: IO a -> MomentIO (Behavior a)

-- | Output. Execute the IO action whenever the event occurs.
--   
--   Note: If two events occur very close to each other, there is no
--   guarantee that the reactimates for one event will have
--   finished before the ones for the next event start executing. This does
--   not affect the values of events and behaviors, it only means
--   that the reactimate for different events may interleave.
--   Fortunately, this is a very rare occurrence, and only happens if
--   
--   
--   
- you call an event handler from inside reactimate,
--   
- or you use concurrency.
--   
--   
--   In these cases, the reactimates follow the control flow of
--   your event-based framework.
--   
--   Note: An event network essentially behaves like a single, huge
--   callback function. The IO action are not run in a separate
--   thread. The callback function will throw an exception if one of your
--   IO actions does so as well. Your event-based framework will
--   have to handle this situation.
reactimate :: Event (IO ()) -> MomentIO ()

-- | The Future monad is just a helper type for the changes
--   function.
--   
--   A value of type Future a is only available in the context of
--   a reactimate but not during event processing.
data Future a

-- | Output. Execute the IO action whenever the event occurs.
--   
--   This version of reactimate can deal with values obtained from
--   the changes function.
reactimate' :: Event (Future (IO ())) -> MomentIO ()

-- | Output, return an Event that is adapted to the changes of a
--   Behavior.
--   
--   Remember that semantically, a Behavior is a function
--   Behavior a = Time -> a. This means that a Behavior does
--   not have a notion of "changes" associated with it. For instance, the
--   following Behaviors are equal:
--   
--   
--   stepper 0 []
--   = stepper 0 [(time1, 0), (time2, 0)]
--   = stepper 0 $ zip [time1,time2..] (repeat 0)
--   
--   
--   In principle, to perform IO actions with the value of a Behavior, one
--   has to sample it using an Event and the apply function.
--   
--   However, in practice, Behaviors are usually step functions. For
--   reasons of efficiency, the library provides a way to obtain an Event
--   that mostly coincides with the steps of a Behavior, so that
--   sampling is only done at a few select points in time. The idea is that
--   
--   
--   changes =<< stepper x e  =  return e
--   
--   
--   Please use changes only in a ways that do not
--   distinguish between the different expressions for the same Behavior
--   above.
--   
--   Note that the value of the event is actually the new value,
--   i.e. that value slightly after this point in time. (See the
--   documentation of stepper). This is more convenient. However,
--   the value will not become available until after event processing is
--   complete; this is indicated by the type Future. It can be used
--   only in the context of reactimate'.
changes :: Behavior a -> MomentIO (Event (Future a))

-- | Impose a different sampling event on a Behavior.
--   
--   The Behavior will have the same values as before, but the event
--   returned by the changes function will now happen simultaneously
--   with the imposed event.
--   
--   Note: This function is useful only in very specific circumstances.
imposeChanges :: Behavior a -> Event () -> Behavior a

-- | Dynamically add input and output to an existing event network.
--   
--   Note: You can perform IO actions here, which is useful if you
--   want to register additional event handlers dynamically.
--   
--   However, if two arguments to execute occur simultaneously, then
--   the order in which the IO therein are executed is unspecified.
--   For instance, in the following code
--   
--   
--   example e = do
--         e1 <- execute (liftIO (putStrLn "A") <$ e)
--         e2 <- execute (liftIO (putStrLn "B") <$ e)
--         return (e1,e2)
--   
--   
--   it is unspecified whether A or B are printed first.
--   
--   Moreover, if the result Event of this function has been garbage
--   collected, it may also happen that the actions are not executed at
--   all. In the example above, if the events e1 and e2
--   are not used any further, then it can be that neither A nor
--   B will be printed.
--   
--   If your main goal is to reliably turn events into IO actions,
--   use the reactimate and reactimate' functions instead.
execute :: Event (MomentIO a) -> MomentIO (Event a)

-- | Lift an IO action into the Moment monad, but defer its
--   execution until compilation time. This can be useful for recursive
--   definitions using MonadFix.
liftIOLater :: IO () -> MomentIO ()

-- | Interpret an event processing function by building an
--   EventNetwork and running it. Useful for testing, but uses
--   MomentIO. See interpret for a plain variant.
interpretFrameworks :: (Event a -> MomentIO (Event b)) -> [Maybe a] -> IO [Maybe b]

-- | Build an Event together with an IO action that can fire
--   occurrences of this event. Variant of newAddHandler.
--   
--   This function is mainly useful for passing callback functions inside a
--   reactimate.
newEvent :: MomentIO (Event a, Handler a)

-- | Build a new Event that contains the result of an IO
--   computation. The input and result events will not be
--   simultaneous anymore, the latter will occur later than the
--   former.
--   
--   Please use the fmap for Event if your computation is
--   pure.
--   
--   Implementation:
--   
--   
--   mapEventIO f e1 = do
--       (e2, handler) <- newEvent
--       reactimate $ (\a -> f a >>= handler) <$> e1
--       return e2
--   
mapEventIO :: (a -> IO b) -> Event a -> MomentIO (Event b)

-- | Build a Behavior together with an IO action that can
--   update this behavior with new values.
--   
--   Implementation:
--   
--   
--   newBehavior a = do
--       (e, fire) <- newEvent
--       b         <- stepper a e
--       return (b, fire)
--   
newBehavior :: a -> MomentIO (Behavior a, Handler a)

-- | Data type that represents a compiled event network. It may be paused
--   or already running.
data EventNetwork

-- | Actuate an event network. The inputs will register their event
--   handlers, so that the networks starts to produce outputs in response
--   to input events.
actuate :: EventNetwork -> IO ()

-- | Pause an event network. Immediately stop producing output. (In a
--   future version, it will also unregister all event handlers for
--   inputs.) Hence, the network stops responding to input events, but it's
--   state will be preserved.
--   
--   You can resume the network with actuate.
--   
--   Note: You can stop a network even while it is processing events, i.e.
--   you can use pause as an argument to reactimate. The
--   network will not stop immediately though, only after the
--   current event has been processed completely.
pause :: EventNetwork -> IO ()

-- | PROVISIONAL. Measure of the number of events in the event network.
--   Useful for understanding space usage.
getSize :: EventNetwork -> IO Int

module Reactive.Banana

-- | Compile the description of an event network into an
--   EventNetwork that you can actuate, pause and so
--   on.
compile :: MomentIO () -> IO EventNetwork
