Haskell Language Reactive-banana Behavior type


Example

To represent continious signals, reactive-banana features Behavior a type. Unlike Event, a Behavior is an Applicative, which lets you combine n Behaviors using an n-ary pure function (using <$> and <*>).

To obtain a Behavior a from the Event a there is accumE function:

main = do
    (inputHandler, inputFire) <- newAddHandler
    compile $ do
        ...
        inputBehavior <- accumE "" $ fmap (\oldValue newValue -> newValue) inputEvent

accumE takes Behavior's initial value and an Event, containing a function that would set it to the new value.

As with Events, you can use fmap to work with current Behaviors value, but you can also combine them with (<*>).

main = do
    (inputHandler, inputFire) <- newAddHandler
    compile $ do
        ...
        inputBehavior  <- accumE "" $ fmap (\oldValue newValue -> newValue) inputEvent
        inputBehavior' <- accumE "" $ fmap (\oldValue newValue -> newValue) inputEvent
        let constantTrueBehavior = (==) <$> inputBehavior <*> inputBehavior'

To react on Behavior changes there is a changes function:

main = do
    (inputHandler, inputFire) <- newAddHandler
    compile $ do
        ...
        inputBehavior  <- accumE "" $ fmap (\oldValue newValue -> newValue) inputEvent
        inputBehavior' <- accumE "" $ fmap (\oldValue newValue -> newValue) inputEvent
        let constantTrueBehavior = (==) <$> inputBehavior <*> inputBehavior'
        inputChanged <- changes inputBehavior

The only thing that should be noted is that changes return Event (Future a) instead of Event a. Because of this, reactimate' should be used instead of reactimate. The rationale behind this can be obtained from the documentation.